3

I know you can find the first and last elements in a treeset. What if I wanted to know what the second or third element was without iterating? Or, more preferable, given an element, figure out it's rank in the treeset.

Thanks

EDIT: I think you can do it using tailset, ie. compare the size of the original set with the size of the tailset. How efficient is tailset?

JPC
  • 8,096
  • 22
  • 77
  • 110

3 Answers3

4

TreeSet does not provide an efficient rank method. I suspect (you can confirm by looking at its source) that TreeSet does not even maintain any extra bits of information (i.e. counts of elements on the left and right subtrees of each node) that one would need to perform such queries in O(log(n)) time. So there does not appear to be any fast method of finding the rank of an element of TreeSet.

If you really really need it, you can either implement your own SortedSet with a balanced binary search tree which allows such queries or modify the TreeSet implementation to create a new implementation which is augmented to allow such queries. Refer to the chapter on augmenting data structures in CLRS for more details about how this can actually be done.

MAK
  • 26,140
  • 11
  • 55
  • 86
  • 1
    This is very interesting. I arrived at this page because I was surprised to notice the JDK tree implementation did not support `select()` and `rank()` and I was wondering why. This makes perfect sense. Without maintaining `size` at every individual `node` level, one cannot provide an efficient O(logn) `rank()` and `select()`. – Srikanth Jun 20 '20 at 13:35
1

There is no other way than Iterator.

Edited:

Try this:

treeSet.higher(treeSet.first());

This should give second element on TreeSet. I'm not sure if this is more optimized then just using Iterator.

Peter Knego
  • 79,991
  • 11
  • 123
  • 154
  • If I know the size of the tailSet, compared to the size of the whole set, I can find the rank that way right? But how efficient is tailSet – JPC Nov 06 '10 at 18:14
1

According to the source of the Sun JDK6 implementation, tailSet(E).size() iterates over the tail set and counts the elements, so this call is O(tail set size).

Christian Semrau
  • 8,913
  • 2
  • 32
  • 39