Count-Weighted Random Sampling with Dynamic Insertions and Removals
Data Structure DesignAuto-graded · 14 test casesLast updated
Design a multiset supporting constant-time insert, remove, and random selection where each element's pick probability is proportional to its frequency.
Build a data structure that maintains a multiset of integers (a collection allowing duplicates) and supports three operations, each running in average O(1) time:
-
insert(val) → bool: Add one copy of
valto the multiset. ReturnTrueif this is the first occurrence ofvalbeing added (the value was not present before), otherwise returnFalse. -
remove(val) → bool: If at least one copy of
valexists in the multiset, remove exactly one copy and returnTrue. Ifvalis not present, returnFalse. -
get_random() → int: Return a uniformly random element from the underlying list of all stored copies. Each stored copy has equal probability of being selected, so a value appearing k times is k times as likely to be picked as a value appearing once.
For example, if the multiset contains [5, 5, 5, 9], calling get_random() should return 5 with probability 3/4 and 9 with probability 1/4.
Implement the structure by writing a driver function that processes a sequence of operations and returns the list of results.
Constraints
-2³¹ ≤ val ≤ 2³¹ - 1- At most
2 × 10⁵total operations will be performed get_random()is never called on an empty multiset
Examples
Example 1
Input: run_multiset_operations(['insert', 'insert', 'insert', 'get_random', 'remove', 'get_random'], [[1], [1], [2], [], [1], []], 7)
Output: [True, False, True, 1, True, 2]
Example 2
Input: run_multiset_operations(['insert', 'insert', 'remove', 'insert', 'get_random', 'remove', 'remove'], [[-4], [0], [-4], [-4], [], [0], [-4], []], 19)
Output: [True, True, True, True, 0, True, True]
Hints
Hint 1
Store all element copies in a list so you can pick a random index in O(1). Use a hash map to track which indices hold each value.
Hint 2
When removing an element, swap it with the last element in the list to avoid shifting. Remember to update the index mapping for the element you moved.
Hint 3
Watch the edge case where the element being removed is already at the last position, or when the swapped element has the same value as the one being removed.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To achieve average O(1) time for all three operations, we combine two data structures:
- A list (dynamic array) storing every element copy. This allows O(1) random access by index.
- A hash map where each key is a value present in the multiset, and each mapped entry is a set of indices where that value appears in the list.
Insert: Append the value to the list and record its new index in the hash map. Check whether the value's key already existed to determine the return value.
Remove: Look up one index holding the target value. To avoid O(n) shifting, perform a swap-with-last trick: overwrite the element at the chosen index with the last element in the list, update the moved element's index set, then pop the last element. If the target value's index set becomes empty, delete its hash map entry. Handle the special case where the removed element is already the last one (no actual swap needed, but bookkeeping still applies).
Get Random: Pick a uniformly random index from [0, len(list)) and return the element at that index. Since each copy occupies exactly one slot, the probability of picking any value is proportional to its occurrence count.
Why It Works
- The list guarantees O(1) random indexing.
- The hash map provides O(1) average-time lookup of where a value lives.
- Swapping with the last element avoids O(n) array shifts while keeping all indices valid.
- Careful index bookkeeping ensures the moved element's index set stays accurate, even when the moved element has the same value as the removed one.
Complexity
- Time: O(1) average for each operation (hash map operations and list append/pop at end are O(1) average; set operations on small index sets are also O(1) average per call).
- Space: O(n) where n is the total number of element copies currently stored.
Solution
import random
from typing import List, Optional
def run_multiset_operations(operations: List[str], arguments: List[List[int]], seed: int) -> List[Optional[int]]:
rng = random.Random(seed)
elements = []
index_map = {}
results = []
for op, args in zip(operations, arguments):
if op == "insert":
val = args[0]
was_absent = val not in index_map
if val not in index_map:
index_map[val] = set()
index_map[val].add(len(elements))
elements.append(val)
results.append(was_absent)
elif op == "remove":
val = args[0]
if val not in index_map or not index_map[val]:
results.append(False)
else:
idx_to_remove = index_map[val].pop()
last_idx = len(elements) - 1
last_val = elements[last_idx]
elements[idx_to_remove] = last_val
if idx_to_remove != last_idx:
index_map[last_val].remove(last_idx)
index_map[last_val].add(idx_to_remove)
elements.pop()
if not index_map[val]:
del index_map[val]
results.append(True)
elif op == "get_random":
random_val = elements[rng.randrange(len(elements))]
results.append(random_val)
return results