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)?
- A. O(n), because a bucket is always a linked list
- B. O(1), because the table resizes to break the collision
- 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)
- 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
- Problem: For each day, how many days until a strictly warmer day (0 if none)? python def wait(t): res, st = [0] len(t), [] for i, x in…
- Problem: The span of a stock on a day is the number of consecutive days up to and including it with price ≤ that day's price. python def…
- Problem: Asteroids move along a line: positive = right, negative = left, |value| = size. When two meet, the smaller explodes; equal sizes…
- Problem: Decode a string where k[s] means s repeated k times (brackets can nest). python def decode(s): st, cur, k = [], "", 0 for c in s…
- Problem: Evaluate an expression with +, −, parentheses and non-negative integers, using a stack of signs. python def calc(s): res, num…
- Problem: Remove duplicate letters so that each letter appears once and the result is the lexicographically smallest possible subsequence…