What is the time complexity of ordered operations in TreeSet?

signalseeker picture signalseeker · Mar 7, 2011 · Viewed 7.5k times · Source

What is the time complexity of the following operations in java.util.TreeSet?

  • first()
  • last()
  • lower()
  • higher()

I would assume that these are constant time but the API makes no guarantees.

Answer

Stephen C picture Stephen C · Mar 7, 2011

Actually, I'd have thought that those operations are all going to be O(logN) for a general implementation.

  • For first() and last() to be O(1) the TreeSet implementation would need to maintain a pointer to the leftmost and rightmost leaf nodes in the tree respectively. Maintaining these adds a constant cost to every insertion and at least a constant cost to every deletion. In reality, the implementation will probably find the left / rightmost nodes on the fly ... which is an O(logN) operation.

  • The lower() and higher() methods have to do the same work as get and are therefore O(logN).

Of course, you can check the source-code yourself to see what actually happens. (As other people have done: see below.)