Insert Delete GetRandom O(1)
Problem
Design a data structure RandomizedSet supporting three operations, each in average O(1) time:
insert(val): addvalif it is not already present; returnTrueif it was added,Falseotherwise.remove(val): removevalif present; returnTrueif it was removed,Falseotherwise.getRandom(): return one of the currently stored values, chosen uniformly at random. This is only called when the set is non-empty.Values are 32-bit signed integers.
Expect on the order of a few hundred thousand operations in total, in any mix.
Examples
insert(7)→True;insert(7)→False;remove(3)→False;insert(3)→True;remove(7)→True;insert(7)→True;getRandom()→3or7, each with probability 1/2.insert(40),insert(50),insert(60),insert(70);remove(70)→True(removing the element at the end of the array);remove(70)→False; the set is now{40, 50, 60}.insert(-9)→True;remove(-9)→True;insert(-9)→True;getRandom()→-9. A value can be re-added after removal.
Hints
- A hash set gives O(1) insert and remove but cannot pick a uniformly random element in O(1). An array can pick a random index but cannot remove an arbitrary element in O(1). Combine them.
- Removing from the middle of an array is O(n) only because of shifting. What if the element you remove is always the last one?
- Keep an array of values plus a map from value to its index. To remove, swap the target with the last element, update the map for the moved element, then pop.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.