← Questions
Set with constant-time insert, delete and get random
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Google's first round (coding), last asked Jan 2026. It tests hash maps, arrays and randomization.
Design a set of unique integers that supports insert, delete and returning a random element, each in average O(1) time. A random element must be uniform over the elements currently in the set.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
add(x: int) -> bool— insertsx;Falseif it was already present. -
remove(x: int) -> bool— deletesx;Falseif it was absent. -
get_random() -> int | None— a uniformly random element;Noneon an empty set (state and justify your choice; raising an error is the other option). - The random source is injectable so tests are deterministic.
Example
add(1) -> True
add(2) -> True
add(2) -> False
remove(1) -> True
remove(3) -> False
get_random() -> 2 # the only element
remove(2) -> True
get_random() -> None
Constraints
- Up to
2 * 10^5operations;-10^9 <= x <= 10^9.
Clarifying questions
- What should
get_randomdo on an empty set? - Must randomness be uniform at every moment, or is approximately uniform acceptable?
- Is the set used by several threads?
What a strong answer covers
- An array of elements plus a hash map from element to its index.
-
removein O(1): move the last element into the removed slot, update its index in the map, pop the end. -
get_random: a uniform random index into the array. - Why a hash set alone cannot return a uniform random element in O(1), and why an array alone cannot delete in O(1).
- Tests: removing the last element, removing the only element, repeated add and remove of the same value.
Follow-ups
- Make it thread-safe: one lock for the whole set (simple, correct, contended), a read-write lock, or finer-grained locking. Explain why per-element locks are hard here, because
removetouches the moved element and the array's end. - Allow duplicates (a multiset) with the same costs.
-
get_randomweighted by a value stored with each element.
Where it's asked
- Google · First round: coding · Last asked Jan 202645 min · Coding in a Google Doc, no syntax highlighting or autocomplete · No AI
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
