Duplicate-Aware Collection with O(1) Random Sampling
Data Structure DesignModel answerLast updated
Design a multiset supporting insert, remove, and uniform random sampling over all occurrences, each in expected O(1) time.
Duplicate-Aware Collection with O(1) Random Sampling
You need to build a collection that stores integers, allows duplicates, and supports three operations, each running in expected O(1) time:
insert(val: int) -> bool: Store one copy ofval. ReturnTrueifvalhad zero copies before this call,Falseotherwise.remove(val: int) -> bool: Erase one copy ofvalif any exist. ReturnTrueif a copy was found and removed,Falseifvalwas absent.getRandom() -> int: Return one element chosen uniformly at random across every stored copy. A value with three copies must be three times as likely to be returned as a value with one copy. You may assume this is never called on an empty collection.
What to implement
class RandomizedCollection:
def __init__(self): ...
def insert(self, val: int) -> bool: ...
def remove(self, val: int) -> bool: ...
def getRandom(self) -> int: ...
Constraints
-2^31 <= val <= 2^31 - 1- At most
2 * 10^5calls across all three methods combined. getRandomis only called when the collection is non-empty.
What is expected in your answer
Explain your choice of underlying data structures and why no single structure is sufficient. Walk through the deletion logic in detail, including what happens when the element you are removing happens to sit at the end of your backing array, and what happens when the value you are relocating during deletion is the same value you are removing. Discuss complexity and any invariants your design must maintain.
Hints
Hint 1
getRandom needs O(1) uniform sampling — think about which data structure lets you pick a random slot directly. A hash map alone cannot do this, but a plain array can.
Hint 2
To delete from an arbitrary position in an array in O(1), overwrite that slot with the last element and shrink the array by one. You just need a way to find the slot for any given value in O(1) — that is where a map from value to index comes in. With duplicates, one value can occupy multiple slots, so the map needs to store a collection of indices.
Hint 3
The trickiest deletion case is when the value you are removing is the same as the value at the end of the array (which you are swapping in to fill the gap). Make sure your index bookkeeping handles the situation where both pointers refer to the same index set before you start modifying it.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
No single data structure handles all three operations in O(1), so the design pairs two structures that each cover the other's blind spot.
Why an array alone is not enough: a dynamic array gives O(1) append and true O(1) random access, which makes getRandom trivial. But deleting an arbitrary element is O(n) unless you use the swap-with-last trick — and to use that trick you need to locate the element's slot in O(1).
Why a hash map alone is not enough: a hash map gives O(1) lookup and deletion, but there is no way to draw a uniformly random key in O(1) because the slots are not densely packed.
The combination:
arr: a flat list storing every occurrence. A value with k copies appears k times.pos: a dict mapping each value to a set of its current indices inarr.
A set of indices (rather than a list) is necessary because, during deletion, you need to remove a specific index from the set — the last index in arr — in O(1). Finding and removing a specific value from a list is O(k).
Insert
Append val to arr. Record the new index in pos[val]. Return whether the set was empty before the append.
getRandom
random.choice(arr). Because every occurrence fills exactly one slot and the array has no holes, this is uniform over occurrences. A value held k times has probability k/n.
Remove
This is the interesting operation. The goal is to eliminate one occurrence of val without leaving a hole in arr.
- Pop any index
ifrompos[val]. Ifpos[val]does not exist, returnFalse. - Let
j = len(arr) - 1be the last index, andlast = arr[j]. - Overwrite slot
iwithlast:arr[i] = last. - Update
pos[last]: addi, then discardj. - Pop the last element from
arr. - If
pos[val]is now empty, delete the key.
The deletion edge cases
Case A — generic (val != last, i != j): val loses index i; last gains i and loses j. Straightforward.
Case B — element is already last (i == j): last == val, and after the pop the slot simply disappears. The update sequence in step 4 becomes: add i to pos[val], then discard i from pos[val]. Net effect: i is gone, which is correct. If you discarded j before adding i, you would leave pos[val] pointing to a slot that no longer exists.
Case C — moved value equals removed value (last == val, i != j): For example, arr = [5, 5], and the set hands us index 0. The index set pos[5] starts as {0, 1}. After the pop() in step 1 it is {1}. Step 4 adds 0 → {0, 1}, then discards 1 → {0}. After the array pop, arr = [5] and pos[5] = {0}. Correct. A common bug is treating pos[val] and pos[last] as separate objects in this case — they are the same set.
The empty-key cleanup in step 6 must run after the step-4 update because in Case C the set is temporarily empty after the pop() but gets repopulated. Cleaning up early would delete a live key.
Invariant
After every operation: for every index k in arr, k ∈ pos[arr[k]]; and every index in every set is a valid index into arr pointing to the correct value. Insert and remove both preserve this invariant.
Complexity
- Time: all three operations are expected O(1). The bound is expected (not worst-case) because dict and set operations are average-case O(1) under Python's hash implementation. List
appendandpopare amortized O(1). - Space: O(n) total, where n is the number of stored occurrences. One array slot and one set entry per occurrence.
Python solution
import random
class RandomizedCollection:
def __init__(self):
self.arr = [] # flat list of every stored occurrence
self.pos = {} # val -> set of indices in arr where val lives
def insert(self, val: int) -> bool:
absent = val not in self.pos
self.pos.setdefault(val, set()).add(len(self.arr))
self.arr.append(val)
return absent
def remove(self, val: int) -> bool:
if val not in self.pos:
return False
i = self.pos[val].pop() # index of one occurrence to remove
j = len(self.arr) - 1 # index of the last element
last = self.arr[j]
# Relocate last into slot i. The add-then-discard order keeps
# correctness when i == j or when last == val (same index set).
self.arr[i] = last
self.pos[last].add(i)
self.pos[last].discard(j)
self.arr.pop()
# Clean up only after updating pos[last], because last may equal
# val (same set), which would repopulate it in the step above.
if not self.pos[val]:
del self.pos[val]
return True
def getRandom(self) -> int:
return random.choice(self.arr)
Quick trace
| Call | arr | pos | Returns |
|---|---|---|---|
insert(1) | [1] | {1:{0}} | True |
insert(1) | [1,1] | {1:{0,1}} | False |
insert(2) | [1,1,2] | {1:{0,1}, 2:{2}} | True |
remove(1) (i=0) | [2,1] | {1:{1}, 2:{0}} | True |
getRandom | — | — | 1 or 2, each p=0.5 |
remove(1) (i=j=1) | [2] | {2:{0}} | True |
Common mistakes
- Using a list of indices instead of a set, making the "discard
j" step O(k). - Discarding
jbefore addingiin the same-value case, which corrupts the index set. - Deleting an empty key before finishing the
lastupdate, incorrectly removing a still-live entry. - Returning
Falseafter checkingarrmembership rather thanposmembership — the former is O(n).