Multiset with O(1) Insert, Delete, and Uniform Random Sampling
Data Structure DesignModel answerLast updated
Build a collection supporting duplicates with constant-time insertion, deletion, and uniform random selection from all stored occurrences.
You need to implement a collection that stores strings and allows the same string to appear multiple times. The collection must support three operations, each running in average O(1) time:
class StringMultiset:
def add(self, s: str) -> bool: ...
def delete(self, s: str) -> bool: ...
def pick_random(self) -> str: ...
Operation specifications:
-
add(s)stores one copy of strings, even ifsalready exists in the collection. ReturnTrueif this is the first occurrence ofsbeing added,Falseifswas already present. -
delete(s)removes exactly one occurrence ofsif any exist. ReturnTrueif an occurrence was successfully removed,Falseifswas not found. -
pick_random()returns one element selected uniformly at random from all stored occurrences. If a string appears k times among n total stored elements, it should be returned with probability k/n.
Assumptions and constraints:
- Strings may have arbitrary length
- Hash operations and string equality checks can be treated as O(1) for complexity analysis
- The collection may be empty when
pick_random()is called (specify your behavior) - Multiple occurrences of the same string must be tracked independently
Example:
ms = StringMultiset()
ms.add("apple") # returns True (first occurrence)
ms.add("apple") # returns False (already present)
ms.add("banana") # returns True
ms.pick_random() # returns "apple" with probability 2/3, "banana" with probability 1/3
ms.delete("apple") # returns True (one occurrence removed)
ms.pick_random() # returns "apple" with probability 1/2, "banana" with probability 1/2
ms.delete("cherry") # returns False (not present)
Hints
Hint 1
Random access suggests storing elements in a contiguous structure where you can index directly
Hint 2
Deletion from the middle of an array is expensive, but swapping with the last element is cheap
Hint 3
You need a way to quickly locate where each string's occurrences are stored
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is supporting uniform random selection while maintaining constant-time insertion and deletion. Random selection requires direct indexing, which points to an array-based structure. However, naive array deletion is O(n) due to shifting. The key insight is to use swap-with-last deletion combined with auxiliary index tracking.
Data Structure Design
Maintain two components:
- Dynamic array
elements: stores all occurrences in arbitrary order - Hash map
positions: maps each unique string to a set of indices where it appears inelements
For example, if elements = ["apple", "banana", "apple"], then positions = {"apple": {0, 2}, "banana": {1}}.
Operations
add(s):
- Append
stoelements(its index will belen(elements) - 1) - Check if
sexists inpositions - Add the new index to
positions[s] - Return whether this was a new key in
positions
Time: O(1) average (hash lookup, set insertion, array append)
delete(s):
- Check if
sexists inpositions; if not, returnFalse - Pick any index from
positions[s](e.g.,pop()one element) - Swap
elements[index]withelements[-1](the last element) - Update
positionsfor the swapped element:- Remove the old position of the last element
- Add
indexas a new position (ifindex != len(elements) - 1)
- Remove the last element from
elements - If
positions[s]is now empty, removesfrom the map - Return
True
Critical edge case: when deleting the last element itself, the swap is a no-op, but you must still update positions correctly. If the last element has the same value as s, both the removal and the position update affect the same set.
Time: O(1) average (hash and set operations are constant time)
pick_random():
- Return
elements[random.randint(0, len(elements) - 1)]
If the collection is empty, either raise an exception or return None based on specification.
Time: O(1)
Correctness of Uniform Sampling
Each stored occurrence occupies exactly one position in elements. A random index selects each position with probability 1/n, so each occurrence is equally likely. If string s appears k times, it occupies k positions, giving probability k/n.
Complexity Analysis
-
Time: All operations are O(1) average, assuming hash operations and set operations (add, remove, pop) are O(1). String hashing is O(length) in theory, but we treat it as O(1) per the problem statement.
-
Space: O(n) for the array plus O(n) for the hash map, where n is the total number of occurrences. Each occurrence appears once in
elementsand its index appears once across all sets inpositions.
Common Mistakes
-
Forgetting to update the swapped element's position: after swapping, you must update
positionsfor the element that moved from the end to the deleted position. -
Incorrect handling when deleting the last element: when
index == len(elements) - 1, the swap is a no-op, but position bookkeeping must still execute correctly. -
Same-value swap: when the deleted element and the last element have the same string value, both updates affect
positions[s]. You must remove the deleted index and (if different) add the new index to the same set. -
Memory leaks in
positions: if a string's occurrence count drops to zero, remove it frompositionsentirely to avoid stale keys.
Implementation Sketch
import random
class StringMultiset:
def __init__(self):
self.elements = []
self.positions = {} # str -> set of indices
def add(self, s: str) -> bool:
is_new = s not in self.positions
if is_new:
self.positions[s] = set()
self.positions[s].add(len(self.elements))
self.elements.append(s)
return is_new
def delete(self, s: str) -> bool:
if s not in self.positions:
return False
# Pick an arbitrary index of s
idx_to_remove = self.positions[s].pop()
last_idx = len(self.elements) - 1
last_element = self.elements[last_idx]
# Swap with last
self.elements[idx_to_remove] = last_element
# Update positions for the swapped element
if idx_to_remove != last_idx:
self.positions[last_element].remove(last_idx)
self.positions[last_element].add(idx_to_remove)
# Remove last element
self.elements.pop()
# Clean up positions map
if not self.positions[s]:
del self.positions[s]
return True
def pick_random(self) -> str:
return self.elements[random.randint(0, len(self.elements) - 1)]
This design efficiently balances random access, fast deletion, and accurate probability distribution.