Insert Delete GetRandom O(1)
LeetCode 380 · Medium · solution, intuition & step-by-step walkthrough
List + index map; delete by swapping with the last element.
This is how I solved Insert Delete GetRandom O(1) (LeetCode 380), a medium problem from the Design pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
A list gives O(1) random picks, a hash map gives O(1) membership. Keep both: the list stores values, the map stores each value's index. To delete in O(1), move the last element into the hole and pop the end.
Approach
- 1
insert: reject duplicates, append, record the index.
- 2
remove: look up the index, overwrite it with the last value, update that value's index, pop the end.
- 3
getRandom: random.choice on the list.
How I solved it
Array + hash mapPythonO(1) per op
class RandomizedSet:
def __init__(self):
self.data = []
self.loc_map={}
def insert(self, val: int) -> bool:
if val in self.loc_map:
return False
self.data.append(val)
self.loc_map[val]=len(self.data)-1
return True
def remove(self, val: int) -> bool:
if val not in self.loc_map:
return False
remove_item_index = self.loc_map.get(val)
last_item = self.data[-1]
self.data[remove_item_index]=last_item
self.loc_map[last_item]=remove_item_index
del self.loc_map[val]
self.data.pop()
return True
def getRandom(self) -> int:
return random.choice(self.data)
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()Insert Delete GetRandom O(1) — FAQ
What is the intuition behind Insert Delete GetRandom O(1)?
A list gives O(1) random picks, a hash map gives O(1) membership. Keep both: the list stores values, the map stores each value's index. To delete in O(1), move the last element into the hole and pop the end.
How do you solve Insert Delete GetRandom O(1) (LeetCode 380)?
1. insert: reject duplicates, append, record the index. 2. remove: look up the index, overwrite it with the last value, update that value's index, pop the end. 3. getRandom: random.choice on the list.
What is the time and space complexity of Insert Delete GetRandom O(1)?
Time: O(1) average per operation. Space: O(n). (Accepted approach: Array + hash map.)
What are common mistakes in Insert Delete GetRandom O(1)?
Update the moved element's index before deleting the removed key (order matters when removing the last element).