1. Hash Map

class RandomizedSet:

    def __init__(self):
        self.numMap = {}
        self.size = 0

    def insert(self, val: int) -> bool:
        if val in self.numMap:
            return False
        self.numMap[val] = 1
        self.size += 1
        return True

    def remove(self, val: int) -> bool:
        if val not in self.numMap:
            return False
        del self.numMap[val]
        self.size -= 1
        return True

    def getRandom(self) -> int:
        idx = random.randint(0, self.size - 1)
        return list(self.numMap.keys())[idx]

Time & Space Complexity

  • Time complexity: O(n)O(n) for getRandom()getRandom(), O(1)O(1) for other function calls.
  • Space complexity: O(n)O(n)

2. Hash Map + List

class RandomizedSet:

    def __init__(self):
        self.numMap = {}
        self.nums = []

    def insert(self, val: int) -> bool:
        if val in self.numMap:
            return False
        self.numMap[val] = len(self.nums)
        self.nums.append(val)
        return True

    def remove(self, val: int) -> bool:
        if val not in self.numMap:
            return False
        idx = self.numMap[val]
        last = self.nums[-1]
        self.nums[idx] = last
        self.numMap[last] = idx
        self.nums.pop()
        del self.numMap[val]
        return True

    def getRandom(self) -> int:
        return random.choice(self.nums)

Time & Space Complexity

  • Time complexity: O(1)O(1) for each function call.
  • Space complexity: O(n)O(n)