Problem : https://leetcode.com/problems/insert-delete-getrandom-o1/
The crux is using the last element of the list to replace the element needs to be removed to meet the requirement of O(1) deleting operation.
import random
class RandomizedSet:
def __init__(self):
"""
Initialize your data structure here.
"""
self.dict = {}
self.list = []
def insert(self, val: int) -> bool:
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
"""
res = val not in self.dict
if res:
self.dict[val] = len(self.list)
self.list.append(val)
return res
def remove(self, val: int) -> bool:
"""
Removes a value from the set. Returns true if the set contained the specified element.
"""
res = val in self.dict
if res:
# use the last element to replace the removed element
index = self.dict[val]
del self.dict[val]
if index != len(self.list) - 1:
self.list[index] = self.list[-1]
# update element index and popup the last element from list
self.dict[self.list[index]] = index
self.list.pop()
return res
def getRandom(self) -> int:
"""
Get a random element from the set.
"""
pick = random.randint(0, len(self.list) - 1)
return self.list[pick]
# 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()