Skip to content
DSA Patterns
Menu
Language
Reservoir SamplingLC #3801 of 6Next →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Insert Delete GetRandom O(1)

Problem (restated)

Design RandomizedSet: insert(val) and remove(val) return whether the set changed; getRandom() returns a uniformly random current value. Average O(1) per call.

Intuition

A hash set is O(1) insert/remove but cannot pick uniformly in O(1). Store values in an array (index is the random draw) and a map value → index. On delete, swap the victim with the tail, update the map, then pop; no hole in the array.

Approaches

Array + hashmap, swap-to-tail

Unverified
Time O(1)Space O(n)

Idea. insert appends and records the index. remove looks up the index, copies the last value into that slot, remaps the last value, pops. getRandom is arr[rand(len)].

Walkthrough. insert 1,2,3 → [1,2,3]. remove 2: swap 3 into index 1 → [1,3]. getRandom is 1 or 3 with equal chance.

Trade-offs. Duplicate insert/remove of a missing value must return false without mutating. Swap-before-delete still works when the victim is already the tail.

Solution
export class RandomizedSet {
  private vals: number[] = [];
  private idx: Map<number, number> = new Map();

  insert(val: number): boolean {
    if (this.idx.has(val)) return false;
    this.idx.set(val, this.vals.length);
    this.vals.push(val);
    return true;
  }

  remove(val: number): boolean {
    if (!this.idx.has(val)) return false;
    const i = this.idx.get(val)!;
    const last = this.vals[this.vals.length - 1]!;
    this.vals[i] = last;
    this.idx.set(last, i);
    this.vals.pop();
    this.idx.delete(val);
    return true;
  }

  getRandom(): number {
    return this.vals[Math.floor(Math.random() * this.vals.length)]!;
  }
}
export class RandomizedSet {
  private vals: number[] = [];
  private idx: Map<number, number> = new Map();

  insert(val: number): boolean {
    if (this.idx.has(val)) return false;
    this.idx.set(val, this.vals.length);
    this.vals.push(val);
    return true;
  }

  remove(val: number): boolean {
    if (!this.idx.has(val)) return false;
    const i = this.idx.get(val)!;
    const last = this.vals[this.vals.length - 1]!;
    this.vals[i] = last;
    this.idx.set(last, i);
    this.vals.pop();
    this.idx.delete(val);
    return true;
  }

  getRandom(): number {
    return this.vals[Math.floor(Math.random() * this.vals.length)]!;
  }
}

Template connection

O(1) get-random on the Reservoir Sampling page: the array is a reservoir you mutate; the hash map is the O(1) contains. Same swap-to-tail as Fisher-Yates.

Reflection

  • A map sends each value to its index, and the values live in an array. To delete, swap with the last entry and pop. A random index is then uniform.
  • After the swap, update both indexes in the map. Leave the old index and it becomes a ghost.
  • Insert of a value already present is false. Delete of a missing value is false. The same value is not stored twice. Deleting the only element leaves the array empty.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

O(1) insert, remove, and uniform getRandom. Array for draws, map for index.

map{ }

arr = []

Key:CurrentActive rangeMatchSettledEliminated