Time complexity of TreeMap operations. — Cracked Java
// Java Collections Framework · TreeMap, NavigableMap, SortedMap
JuniorTheory

Time complexity of TreeMap operations.

Every keyed operation on TreeMap is O(log n) in the worst case — including the navigation methods like floorKey/ceilingKey. Iteration is O(n). There is no O(1) fast path the way HashMap has, because the data structure is fundamentally a tree.

The table

OperationBestAverageWorstNote
getO(log n)O(log n)O(log n)tree descent
putO(log n)O(log n)O(log n)descend + at most O(log n) rotations
removeO(log n)O(log n)O(log n)find + recolor/rotate to fix invariants
containsKeyO(log n)O(log n)O(log n)same as get
containsValueO(n)O(n)O(n)linear scan; no index on values
firstKey / lastKeyO(log n)O(log n)O(log n)leftmost / rightmost descent
floorKey / ceilingKeyO(log n)O(log n)O(log n)tree descent with bookkeeping
higherKey / lowerKeyO(log n)O(log n)O(log n)strict variants of floor/ceiling
subMap / headMap / tailMapO(1)O(1)O(1)returns a view; no copy
iteration (full)O(n)O(n)O(n)in-order traversal
sizeO(1)O(1)O(1)cached counter

A few subtleties

  • containsValue is O(n) — there's no secondary index on values. Don't rely on it for hot paths.
  • subMap is O(1) but the resulting view's size() is O(n) — it has to count by walking, because the backing tree's size counter covers the whole map, not the range.
  • Range iteration is O(k + log n), where k is the number of entries returned: O(log n) to find the start, plus k tree-successor steps.
  • put rotations are bounded at O(log n) total in the worst case, but amortised, recolorings happen far more often than rotations — rotations average O(1) per insert in practice.

How does it compare to HashMap?

OperationBestAverageWorstNote
get (avg)HashMap: O(1)HashMap: O(1)TreeMap: O(log n)HashMap is faster for plain lookup
get (worst)HashMap: O(log n)TreeMap: O(log n)Both O(log n)HashMap's worst case = TreeMap's normal case
ordered iterationTreeMap: O(n)TreeMap: O(n)HashMap: needs sort, O(n log n)TreeMap wins decisively
range queryTreeMap: O(log n + k)TreeMap: O(log n + k)HashMap: O(n)HashMap has no native range support

Mark your status