Insert Delete GetRandom O(1)
Problem
Implement a data structure that supports insert, remove, and getRandom operations in average O(1) time.
- −2³¹ ≤ val ≤ 2³¹ - 1
- At most 2 * 10⁵ calls will be made to insert, remove, and getRandom.
- There will be at least one element in the data structure when getRandom is called.
Example
insert(1), insert(2), getRandom(), remove(1), insert(2), getRandom()[true, true, 1 or 2, true, false, 2]Initially, the set is empty. insert(1) returns true because 1 was not present. insert(2) returns true because 2 was not present. getRandom() returns either 1 or 2 with equal probability. remove(1) returns true because 1 was present and removed. insert(2) returns false because 2 was already present. getRandom() now returns 2 because it is the only element.
Approach
Straightforward Solution
A naive approach uses a list for storage and a set for membership. Insert and membership checks are O(1) on average, and getRandom is O(1), but removing a value from the middle of the list is O(n) because the list must find and/or shift elements.
Core Observation
The fundamental challenge is to support insert, remove, and getRandom in average O(1) time. Arrays provide O(1) random access, but removing from the middle takes O(n) because elements must shift. Hash maps provide O(1) lookup, insertion, and deletion, but they do not support O(1) random access by index. Combining an array with a value-to-index hash map gives all three operations efficiently.
Path to Optimal
The key insight is to maintain a list for O(1) random access and a hash map from value to its index in the list. To remove an element in O(1), swap it with the last element in the list, update the hash map accordingly, then pop the last element. This avoids shifting elements and maintains consistent indexing. Insert simply appends to the list and updates the map. getRandom uses the list's O(1) random access.
Optimal Approach
Use a list to store values and a hash map to store each value's index in the list. For insert, check if the value exists; if not, append it to the list and record its index. For remove, check if the value exists; if so, swap it with the last element in the list, update the map for the swapped element, pop the last element, and delete the removed value from the map. For getRandom, return a random element from the list using O(1) random access. This guarantees average O(1) time for all operations.
Time
O(1) average
Insert and remove operations perform constant-time hash map lookups and updates, and list append/pop operations are O(1). The swap during removal is a constant-time operation. getRandom uses random.choice on a list, which is O(1).
Space
O(n)
The data structure stores all inserted elements in a list and a hash map, both scaling linearly with the number of elements. This space is necessary to maintain O(1) operations.
Pattern Spotlight
Hash Maps (Index Mapping with Array)
Combine a hash map for O(1) membership and index tracking with an array for O(1) random access; perform removals by swapping the target element with the last element to maintain O(1) deletion without disrupting array order.
Solution
| 1 | import random |
| 2 | |
| 3 | class RandomizedSet: |
| 4 | |
| 5 | def __init__(self): |
| 6 | self.values = [] |
| 7 | self.index = {} |
| 8 | |
| 9 | def insert(self, val: int) -> bool: |
| 10 | if val in self.index: |
| 11 | return False |
| 12 | |
| 13 | self.index[val] = len(self.values) |
| 14 | self.values.append(val) |
| 15 | return True |
| 16 | |
| 17 | def remove(self, val: int) -> bool: |
| 18 | if val not in self.index: |
| 19 | return False |
| 20 | |
| 21 | remove_index = self.index[val] |
| 22 | last_value = self.values[-1] |
| 23 | |
| 24 | self.values[remove_index] = last_value |
| 25 | self.index[last_value] = remove_index |
| 26 | |
| 27 | self.values.pop() |
| 28 | del self.index[val] |
| 29 | |
| 30 | return True |
| 31 | |
| 32 | def getRandom(self) -> int: |
| 33 | return random.choice(self.values) |
Step-by-Step Solution
Initialize List and Hash Map to Track Values and Indices
| 6 | self.values = [] |
| 7 | self.index = {} |
Objective
To set up the foundational data structures that enable constant-time insertions, removals, and random access.
Key Insight
Using a list allows O(1) random access and efficient appends, while a hash map tracks each value's index in the list for O(1) membership checks and index retrieval. This combination is essential to achieve the required average O(1) time complexity for all operations.
Interview Quick-Check
Core Logic
The list stores the actual values, enabling O(1) random access, while the hash map stores value-to-index mappings for O(1) membership and index lookup.
Common Pitfalls & Bugs
Forgetting to initialize both data structures or mixing their responsibilities can lead to inefficient operations.
Insert Values by Appending and Recording Index if Absent
| 10 | if val in self.index: |
| 11 | return False |
| 13 | self.index[val] = len(self.values) |
| 14 | self.values.append(val) |
| 15 | return True |
Objective
To add a new value to the data structure only if it does not already exist, maintaining O(1) insertion time.
Key Insight
Checking the hash map for existence prevents duplicates. Appending to the list is O(1), and recording the index in the map ensures quick future lookups. This approach avoids costly searches or shifts.
Interview Quick-Check
Core Logic
Insert first checks if the value exists in the map; if not, it appends to the list and updates the map with the new index.
Common Pitfalls & Bugs
Inserting duplicates without checking the map breaks the uniqueness constraint and can corrupt the data structure.
Remove Values by Swapping with Last Element and Updating Map
| 18 | if val not in self.index: |
| 19 | return False |
| 21 | remove_index = self.index[val] |
| 22 | last_value = self.values[-1] |
| 24 | self.values[remove_index] = last_value |
| 25 | self.index[last_value] = remove_index |
| 27 | self.values.pop() |
| 28 | del self.index[val] |
| 30 | return True |
Objective
To remove a value in O(1) time by swapping it with the last element and updating the index map accordingly.
Key Insight
Direct removal from the middle of a list is O(n) due to shifting. Swapping the target with the last element and popping avoids shifting. Updating the map for the swapped element maintains correct indexing. Deleting the removed value from the map finalizes the removal.
Interview Quick-Check
Core Logic
Removal swaps the target element with the last element in the list, updates the swapped element's index in the map, pops the last element, and deletes the target from the map.
State & Boundaries
Check if the value exists before removal to avoid errors.
Common Pitfalls & Bugs
Failing to update the swapped element's index in the map leads to incorrect mappings and potential bugs.
Return a Random Element Using O(1) List Access
| 33 | return random.choice(self.values) |
Objective
To retrieve a random element from the current set in O(1) time.
Key Insight
Since the values are stored in a list, random.choice can select an element uniformly at random in constant time. This leverages the list's O(1) indexing property.
Interview Quick-Check
Core Logic
getRandom uses random.choice on the list to return a uniformly random element in O(1) time.
State & Boundaries
Assumes the list is non-empty, as guaranteed by problem constraints.
Line Analysis
This solution has 7 Critical lines interviewers watch for.
self.values[remove_index] = last_value
Overwrite the element at remove_index with the last value.
Swapping the target with the last element avoids costly shifting and maintains list integrity for O(1) removal.
self.index[last_value] = remove_index
Update the hash map to reflect the last value's new index.
Maintaining accurate index mappings is critical to prevent inconsistencies and bugs in future operations.
self.index = {}
Initialize an empty hash map to store value-to-index mappings.
The hash map enables O(1) average-time membership checks and index retrieval, which are critical for efficient insert and remove operations.
self.index[val] = len(self.values)
Record the index of the new value as the current length of the list.
Storing the index before appending ensures the map correctly reflects the position of the new value in the list.
remove_index = self.index[val]
Retrieve the index of the value to remove.
Knowing the index allows direct access to the element in the list for efficient removal.
del self.index[val]
Delete the removed value from the hash map.
Removing the value from the map finalizes the removal and prevents stale references.
return random.choice(self.values)
Return a random element from the list using random.choice.
Using the list's O(1) random access property, this returns a uniformly random element efficiently.
self.values = []
Initialize an empty list to store inserted values.
The list provides O(1) random access and efficient appends, which are essential for the getRandom operation and insertions.
if val in self.index:
Check if the value already exists in the hash map.
Preventing duplicates is necessary to maintain the set property and ensure correctness of insert and remove operations.
self.values.append(val)
Append the new value to the list.
Appending is O(1) and adds the value to the data structure, enabling random access and future operations.
if val not in self.index:
Check if the value exists in the hash map before removal.
Ensures that removal only proceeds if the value is present, preventing errors and maintaining correctness.
last_value = self.values[-1]
Retrieve the last value in the list.
The last element will be swapped with the element to remove to enable O(1) deletion.
self.values.pop()
Remove the last element from the list.
Popping the last element is O(1) and completes the removal process after the swap.
return False
Return False if the value is already present.
This early return enforces the uniqueness constraint and avoids unnecessary modifications.
return False
Return False if the value is not present.
Early exit avoids unnecessary operations and signals that removal was unsuccessful.
return True
Return True to indicate successful insertion.
Signaling success confirms the value was not previously present and has been added.
return True
Return True to indicate successful removal.
Signals that the value was present and has been removed correctly.
Test Your Understanding
Why does swapping the element to remove with the last element in the list enable O(1) removal?
Swapping moves the element to remove to the end of the list, allowing it to be popped in O(1) time without shifting other elements. Updating the hash map for the swapped element maintains correct indexing, preserving the integrity of the data structure.
Related Problems
Hash Maps pattern
Don't just read it. Drill it.
Reconstruct Insert Delete GetRandom O(1) from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the Insert Delete GetRandom O(1) drill