The intuition would be to create a set for O(1) operation. However, since there is the function getRandom(), creating a set is not efficient as we would first need to convert to list, which will be an overhead for the whole code. This is because set is actually not random as when using integers, elements are popped from the set in the order they appear in the underlying hashtable.
Use a dict and a list
Dict as {int element: index}, and list to keep track of unique int elements
When remove is called, swap the last element of the list with the to-be-removed element
Swap the index of the two elements in the dictionary's index
Pop from the list, and remove from the dict
import random
class RandomizedSet:
def __init__(self):
self.d = {}
self.l = []
def insert(self, val: int) -> bool:
if val not in self.d:
# Store the index of the int ele
self.d[val] = len(self.l)
self.l.append(val)
return True
return False
def remove(self, val: int) -> bool:
if val not in self.d:
return False
l_ele = self.l[-1]
r_index = self.d[val]
# Replace the index
self.d[l_ele] = r_index
self.l[r_index] = l_ele
# Remove from list and dict
self.l[-1] = val
self.l.pop()
self.d.pop(val)
return True
def getRandom(self) -> int:
return random.choice(self.l)
# 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()
Approach
https://leetcode.com/problems/insert-delete-getrandom-o1/description/
The intuition would be to create a set for
O(1)
operation. However, since there is the functiongetRandom()
, creating a set is not efficient as we would first need to convert to list, which will be an overhead for the whole code. This is because set is actually not random as when using integers, elements are popped from the set in the order they appear in the underlying hashtable.{int element: index}
, and list to keep track of unique int elementsExample
n: array size
O(1)
with pop, add and get random operationO(n)
with dict and list