We can use subMap(key, true, key, true) instead, which is O(1)
This is correct
and iterating this sub map is also O(1).
O(n) comes from the question. The answer says nothing to imply this, which is good, because it's not true.
Time complexity of iterating a subtree is O(log n + k), where n
is the number of elements in the whole map, and k
is the number of elements in the sub-map. In other words, it still takes O(log n) to get to the first position when you start iterating. Look up getFirstEntry()
implementation to see how it is done.
This brings the overall complexity of your approach to O(log n), but it is bound to be slower than a simple get
, because an intermediate object is created and discarded in the process.