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
UnverifiedIdea. 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.
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.