RandomizedSet in $O(1)$ Time: Dynamic Array + Index Hash Map
A standard array gives $O(1)$ random access (getRandom) and $O(1)$ amortized push/pop at the back, but deleting an arbitrary element takes $O(n)$ because later elements must shift. A hash map gives $O(1)$ lookup, insert, and delete, but cannot pick a uniformly random element directly.
Combining a dynamic array (values) with a hash map (index_map: val -> index in values) gives $O(1)$ average time for insert, remove, and getRandom:
insert(val): Ifvalis already inindex_map, returnfalse. Otherwise appendvaltovaluesat indexlen(values), recordindex_map[val] = idx, and returntrue.remove(val): Ifvalis not inindex_map, returnfalse. Otherwise swap-and-pop—move the last element fromvalues[-1]intoval’s slot (target_idx), updateindex_map[last_val] = target_idx, pop the last element fromvalues, erasevalfromindex_map, and returntrue.getRandom(): Pick a uniformly random indexrin[0, len(values) - 1]and returnvalues[r].
Why Swap-and-Pop Keeps $O(1)$ Without Breaking Indices
Suppose values = [10, 20, 30, 40] and index_map = {10: 0, 20: 1, 30: 2, 40: 3}, and we call remove(20):
target_idx = index_map[20](1), andlast_val = values.pop()(40).- If
target_idx < len(values)(meaning we didn’t just pop the last element itself):- Set
values[target_idx] = last_val(values[1] = 40). - Update
index_map[last_val] = target_idx(index_map[40] = 1).
- Set
- Delete
20fromindex_mapand returntrue.
Edge case: if val is already the last element in values, popping it removes it directly without touching any other index. Be careful to handle target_idx == len(values) - 1 cleanly (either check if target_idx < len(values) after popping, or overwrite before popping when target_idx != last_idx).
Code Implementation
Python Solution
import random
class RandomizedSet:
def __init__(self) -> None:
self.values: list[int] = []
self.index_map: dict[int, int] = {}
def insert(self, val: int) -> bool:
if val in self.index_map:
return False
self.index_map[val] = len(self.values)
self.values.append(val)
return True
def remove(self, val: int) -> bool:
if val not in self.index_map:
return False
target_idx = self.index_map[val]
last_val = self.values[-1]
# Move last element into the removed slot
self.values[target_idx] = last_val
self.index_map[last_val] = target_idx
# Remove the trailing element
self.values.pop()
del self.index_map[val]
return True
def getRandom(self) -> int:
return random.choice(self.values)
C++ Solution
#include <vector>
#include <unordered_map>
#include <random>
class RandomizedSet {
private:
std::vector<int> values;
std::unordered_map<int, int> index_map;
std::mt19937 rng;
public:
RandomizedSet() : rng(std::random_device{}()) {}
bool insert(int val) {
if (index_map.find(val) != index_map.end()) {
return false;
}
index_map[val] = static_cast<int>(values.size());
values.push_back(val);
return true;
}
bool remove(int val) {
auto it = index_map.find(val);
if (it == index_map.end()) {
return false;
}
int target_idx = it->second;
int last_val = values.back();
values[target_idx] = last_val;
index_map[last_val] = target_idx;
values.pop_back();
index_map.erase(it);
return true;
}
int getRandom() {
std::uniform_int_distribution<int> dist(0, static_cast<int>(values.size()) - 1);
return values[dist(rng)];
}
};
Complexity
| Operation | Average Time | Worst-Case Time | Auxiliary Space |
|---|---|---|---|
insert(val) |
$O(1)$ | $O(n)$ (hash table rehash / array resize) | $O(1)$ per element |
remove(val) |
$O(1)$ | $O(n)$ (hash collision / rehash) | $O(1)$ |
getRandom() |
$O(1)$ | $O(1)$ | $O(1)$ |
Overall space complexity across $k$ stored elements is $O(k)$ for both the array and the index hash map.
