Data Structures & AlgorithmsHardAmazon · Microsoft OA

In Java 8+, many keys that are Comparable and all land in ONE HashMap bucket. What is the worst-case cost of get() on that bucket once it holds n keys (n large)?

  1. A. O(n), because a bucket is always a linked list
  2. B. O(1), because the table resizes to break the collision
  3. C. O(log n), because the bucket is converted into a red-black tree once it holds 8 or more entries (and the table has at least 64 buckets)
  4. D. O(n log n), because the tree must be rebuilt on each lookup

Correct answer: C. O(log n), because the bucket is converted into a red-black tree once it holds 8 or more entries (and the table has at least 64 buckets)

Since Java 8, a bucket is 'treeified' when its list reaches TREEIFY_THRESHOLD = 8 and the capacity is at least 64, bounding lookups by O(log n). Resizing cannot help when keys have equal hash codes, which is how hash-flooding attacks work.

More Coding Interview Problems questions

Exams that ask this topic