Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TreeMap lastKey lookup time

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.

like image 950
Arjun Patel Avatar asked Dec 08 '14 18:12

Arjun Patel


2 Answers

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).

like image 84
Sergey Kalinichenko Avatar answered Nov 10 '22 20:11

Sergey Kalinichenko


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.

like image 24
John Bollinger Avatar answered Nov 10 '22 20:11

John Bollinger