Quora interview question
Key-value map with average constant-time put, remove and get-random
- Company:
- Quora
- Type:
- Coding
- Difficulty:
- Medium
- Reported:
- June 2, 2026
Problem
Design a key-value map that supports these operations in average O(1) time:
put(key, value): insert the key or overwrite its value.get(key): return the value, orNoneif the key is absent.remove(key): delete the key; returnTrueif it existed, otherwiseFalse.get_random(): return a uniformly random(key, value)pair among the keys currently stored. Raise an error when the map is empty.
Example 1
Input: put("a", 1), put("b", 2), remove("a"), get("a"), get_random()
Output: None, None, True, None, ("b", 2)
After removing "a", the only remaining pair is ("b", 2), so the random pick must return it.
Example 2
Input: put("x", 5), put("x", 7), get("x"), remove("y")
Output: None, None, 7, False
The second put overwrites the value; removing a missing key returns False.
Constraints
- Up to 2 * 10^5 operations.
- Keys are hashable; values are arbitrary.
- Each existing key must be returned by
get_randomwith equal probability.
Reported by candidates or drawn from publicly available sources, and rewritten in our own words. Pathwise Prep does not publish confidential assessment content. Report a concern