SDE & MLE Prep

380. Insert Delete GetRandom O(1)

Problem

Design RandomizedSet with insert(val) and remove(val) (each returns whether the set changed) and getRandom() (a uniformly random current element, never called on an empty set), all in O(1) average time.

Example: insert(1) → true, remove(2) → false, insert(2) → true, getRandom() → 1 or 2, remove(1) → true, getRandom() → 2

Values live in an array (O(1) random pick); a map stores each value's index. To delete, move the last element into the hole and pop the end.

vals [5, 8, 2, 9]   idx {5:0, 8:1, 2:2, 9:3}
remove 8: move 9 into slot 1 -> [5, 9, 2]  idx {5:0, 9:1, 2:2}

Complexity: O(1) average per operation.

class RandomizedSet:
    def __init__(self):
        self.vals, self.idx = [], {}

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

    def remove(self, val: int) -> bool:
        if val not in self.idx:
            return False
        i, last = self.idx.pop(val), self.vals.pop()
        if i < len(self.vals):            # removed element wasn't the last one
            self.vals[i] = last
            self.idx[last] = i
        return True

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