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.
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.
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
.
According to the implementation in the Open JDK, it is O(log N):
The
lastKey()
callsgetLastEntry()
, 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).