7

What is the time complexity of TreeMap.lastKey() part of the SortedMap interface?

The oracle docs mention this about TreeMaps:

This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.

Arjun Patel
  • 236
  • 2
  • 16
  • 1
    It should be O(log(n)) too. It is mostly balanced and requires going to the right always. – Gábor Bakos Dec 08 '14 at 18:56
  • You can also look at the source code, to see how it's implemented. The answer would be pretty straightforward after. – Alexis C. Dec 08 '14 at 18:57
  • I see. Is there an elegant way to always keep track of the last key/value even after deleting an object from the map? Maybe with the maps entrySet? – Arjun Patel Dec 08 '14 at 18:58
  • @ArjunPatel Is O(logn) too large? What is your usecase? – Gábor Bakos Dec 08 '14 at 19:00
  • You can track the map's maximum key by wrapping / instrumenting all the map's mutation methods (don't forget the iterator's `remove()` method and the mutators of the submaps, and *their* iterators and submaps, etc.). That's certainly not elegant, though, and it will degrade performance, especially of the multi-element removal methods. – John Bollinger Dec 08 '14 at 19:05

2 Answers2

9

According to the implementation in the Open JDK, it is O(log N):

public K lastKey() {
    return key(getLastEntry());
}
final Entry<K,V> getLastEntry() {
    Entry<K,V> p = root;
    if (p != null)
        while (p.right != null)
            p = p.right;
    return p;
}

The lastKey() calls getLastEntry(), which continues to take the right subtree until there are no further nodes to take. Since the implementation maintains the tree in a balanced state, the number of iterations is O(log N).

Sergey Kalinichenko
  • 675,664
  • 71
  • 998
  • 1,399
1

If TreeMap can guarantee O(log(n)) for containsKey() (as it does), then it should be able to do lastKey() in O(log(n)) as well. Any tree structure that can be certain to yield O(log(n)) key lookups can also support finding the maximum key in O(log(n)).

Although nothing inherently rules out a brain-dead implementation that does worse, I think it's pretty safe to discount that possibility for java.util.TreeMap.

John Bollinger
  • 121,924
  • 8
  • 64
  • 118