Faaez Razeen

Insert Delete GetRandom O(1)

  • 2 min read
  • LC-Medium

3 years ago

Solution

TimeSpaceExplanation
O()O()
class RandomizedSet: def __init__(self): self.v_map = {} self.values = [] def insert(self, val: int) -> bool: if val not in self.v_map: self.values.append(val) idx = len(self.values) - 1 self.v_map[val] = idx return True return False def remove(self, val: int) -> bool: if val in self.v_map: idx = self.v_map[val] n = len(self.values) repl_val = self.values[n - 1] self.values[idx] = repl_val self.v_map[repl_val] = idx self.values.pop() del self.v_map[val] return True return False def getRandom(self) -> int: n = len(self.values) idx = randint(0, n - 1) return self.values[idx]