Lottery Bucket with Constant-Time Operations and Duplicates
Data Structure DesignModel answerLast updated
Build a data structure supporting O(1) add, remove, and uniform random selection where duplicate entries are treated as separate items.
You're implementing a lottery bucket system. Players can drop entries (represented as short strings) into the bucket, and the same entry identifier can appear multiple times — each occurrence counts as a separate, independent item in the bucket.
Your data structure must support three operations:
class LotteryBucket:
def add(self, entry: str) -> bool: ...
def extract(self, entry: str) -> bool: ...
def pick_random(self) -> str: ...
-
add(entry)places one additional item with this identifier into the bucket. ReturnsTrueif this is the first time this particular identifier has been added to the bucket,Falseif items with this identifier were already present. -
extract(entry)attempts to remove exactly one item with this identifier from the bucket. ReturnsTrueif an item was successfully removed,Falseif no items with this identifier exist in the bucket. -
pick_random()returns the identifier of one randomly selected item from the bucket, where every individual item has equal probability of selection. For instance, if the bucket contains 5 total items and 2 of them share identifier "X", then "X" should be selected with probability 2/5.
All three operations must achieve average O(1) time complexity.
Example
bucket = LotteryBucket()
bucket.add("TICKET-A") # True (first occurrence of TICKET-A)
bucket.add("TICKET-A") # False (TICKET-A already exists)
bucket.add("TICKET-B") # True
bucket.extract("TICKET-A") # True -> one TICKET-A removed, one remains
bucket.extract("TICKET-C") # False -> not present
bucket.pick_random() # "TICKET-A" or "TICKET-B", each with 50% probability
Constraints
- The system will process up to 10^5 total operations across all three methods.
- Entry identifiers are short strings. The same identifier may exist in multiple copies simultaneously.
pick_random()will only be called when at least one item exists in the bucket.- For complexity analysis, treat string hashing and comparison as O(1) operations.
Design Considerations
Your solution should explain:
- How you ensure
pick_random()gives every physical item equal selection probability - How you remove a specific item without scanning or reorganizing the entire collection
- Why your approach correctly handles edge cases like removing duplicates or extracting the most recently added item
Hints
Hint 1
Store every individual item in a contiguous structure so you can select by random index
Hint 2
Use a lookup map to track where each identifier appears, enabling fast removal without scanning
Hint 3
When removing an item creates a gap, fill it by moving another item — but remember to update that moved item's location in your lookup map
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is to combine a dynamic array with a reverse-lookup index. This hybrid structure enables both uniform random access and constant-time removal.
Core Data Structures
-
Dynamic array (
items: list[str]): Store every individual item in a single flat list. Each position represents one physical entry, so duplicates naturally occupy multiple positions. -
Position index (
location_map: dict[str, set[int]]): Map each distinct identifier to the set of all array indices currently holding it.
Operation Implementations
Adding an item:
- Append the identifier to the end of the array
- Record this new index in the location map
- Check whether this identifier already had entries (determines the return value)
Extracting an item:
- Look up the identifier in the location map
- If no positions exist, return
False - Pick any position from the set (they're equivalent)
- Use swap-with-last deletion: move the final array element into the gap, then shrink the array
- Update the location map: remove the old position, add the new position for the moved element (unless it was already at the end)
Random selection:
- Generate a random index within the array bounds
- Return the identifier at that position
Why This Achieves O(1)
Each operation performs a fixed number of steps:
add: one append + one set insertion + one map lookupextract: one map lookup + one set operation + one array swap + one set update + one array poppick_random: one random integer generation + one array access
All are constant time on average (hash operations have expected O(1) cost).
Fairness Guarantee
The array contains exactly one slot per physical item currently in the bucket. No slots are empty, no slots are double-counted. When pick_random() selects a uniformly random index from 0 to n-1 (where n is the array size), each of the n items has exactly 1/n probability of selection.
If identifier "X" occupies k positions in an array of size n, then "X" is selected with probability k/n — precisely the proportion of items it represents.
Edge Cases and Correctness
Removing the last item of an identifier: The position set becomes empty. The next add of that identifier correctly returns True because the set is empty (treated as non-existent).
Extracting the final array element: When the target index equals the last index, the swap is a no-op. The guard if idx != last_idx prevents unnecessary bookkeeping updates.
Moving an item that shares the same identifier as the removed one: The position map update still works correctly because we're modifying a set — removing the old index and adding the new one, even if both belong to the same identifier.
Multiple extractions of duplicates: Each extraction removes exactly one position from the set for that identifier, correctly handling any number of duplicates.
Complexity Analysis
- Time: O(1) average for all operations
- Space: O(n + m) where n is the total number of items currently in the bucket and m is the number of distinct identifiers
Implementation
import random
class LotteryBucket:
def __init__(self):
self.items: list[str] = []
self.location_map: dict[str, set[int]] = {}
def add(self, entry: str) -> bool:
is_first_occurrence = entry not in self.location_map or not self.location_map[entry]
self.items.append(entry)
new_index = len(self.items) - 1
if entry not in self.location_map:
self.location_map[entry] = set()
self.location_map[entry].add(new_index)
return is_first_occurrence
def extract(self, entry: str) -> bool:
if entry not in self.location_map or not self.location_map[entry]:
return False
# Remove an arbitrary occurrence
target_index = next(iter(self.location_map[entry]))
self.location_map[entry].remove(target_index)
# Swap with last element
last_index = len(self.items) - 1
last_entry = self.items[last_index]
self.items[target_index] = last_entry
# Update location map for moved element (if it wasn't already the last)
if target_index != last_index:
self.location_map[last_entry].remove(last_index)
self.location_map[last_entry].add(target_index)
self.items.pop()
return True
def pick_random(self) -> str:
return random.choice(self.items)
Common Mistakes
- Using only a hash map with counts: This loses the ability to do uniform random selection in O(1), since you'd need to iterate or do weighted sampling.
- Forgetting to update the location map when swapping: The moved element's position must be updated, otherwise future extractions will reference an invalid index.
- Not handling the case where the removed element is already last: The swap becomes self-assignment, but the bookkeeping logic must account for this.
- Treating identifiers as unique: The problem explicitly allows duplicates, requiring a set of positions per identifier rather than a single position.