sagelearnai

Insert Delete GetRandom O(1)

Difficulty: Medium · Pattern: Hashing · LeetCode #380

Design RandomizedSet with average O(1) operations:

  • insert(val): add if absent; return true if inserted, else false.
  • remove(val): remove if present; return true if removed, else false.
  • getRandom(): return a uniformly random element (at least one exists).

(The tests only call getRandom when the set has a single element, so the output is deterministic.)

Hints

  1. A hash set gives O(1) insert/remove but no O(1) random access.
  2. An array gives O(1) random access but O(n) removal from the middle, unless you swap the element with the last one first.

Approach

Keep vals (an array) and pos (a map from value to its index in vals). Insert: append the value and record its index. Remove: move the last element into the removed slot (update its index in the map), pop the last element, and delete the value from the map. getRandom: pick a random index of vals. All average O(1).

Complexity

Time: O(1) average per operation. Space: O(n).

Python solution
import random

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

    def insert(self, val):
        if val in self.pos:
            return False
        self.pos[val] = len(self.vals); self.vals.append(val)
        return True

    def remove(self, val):
        if val not in self.pos:
            return False
        i, last = self.pos[val], self.vals[-1]
        self.vals[i], self.pos[last] = last, i
        self.vals.pop(); del self.pos[val]
        return True

    def getRandom(self):
        return random.choice(self.vals)
JavaScript solution
class RandomizedSet {
  constructor() { this.vals = []; this.pos = new Map(); }
  insert(val) { if (this.pos.has(val)) return false; this.pos.set(val, this.vals.length); this.vals.push(val); return true; }
  remove(val) {
    if (!this.pos.has(val)) return false;
    const i = this.pos.get(val), last = this.vals[this.vals.length - 1];
    this.vals[i] = last; this.pos.set(last, i); this.vals.pop(); this.pos.delete(val);
    return true;
  }
  getRandom() { return this.vals[Math.floor(Math.random() * this.vals.length)]; }
}