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.
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).
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With