Design Data Structures · Pattern 5 of 10
Hash map + array: O(1) insert, delete and random
An array can return a random element in O(1) but cannot delete from the middle. A hash map from value to index fixes that: move the last element into the hole, update its index, then pop the end.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Insert, delete and get a random element, all in O(1)
- Remember the last time something was seen
- A few fixed categories with a counter each
The template
class RandomizedSet {
List<Integer> vals = new ArrayList<>();
Map<Integer, Integer> idx = new HashMap<>(); // value -> its index in vals
Random rnd = new Random();
boolean insert(int val) {
if (idx.containsKey(val)) return false;
idx.put(val, vals.size());
vals.add(val);
return true;
}
boolean remove(int val) {
Integer i = idx.remove(val);
if (i == null) return false;
int last = vals.remove(vals.size() - 1); // removing the end is O(1)
if (i < vals.size()) { // fill the hole with the last value
vals.set(i, last);
idx.put(last, i);
}
return true;
}
int getRandom() { return vals.get(rnd.nextInt(vals.size())); }
} import random
class RandomizedSet:
def __init__(self):
self.vals, self.idx = [], {} # idx: value -> its index in vals
def insert(self, val):
if val in self.idx:
return False
self.idx[val] = len(self.vals)
self.vals.append(val)
return True
def remove(self, val):
if val not in self.idx:
return False
i, last = self.idx.pop(val), self.vals.pop() # popping the end is O(1)
if i < len(self.vals): # fill the hole with the last value
self.vals[i] = last
self.idx[last] = i
return True
def getRandom(self):
return random.choice(self.vals) class RandomizedSet {
vector<int> vals;
unordered_map<int, int> idx; // value -> its index in vals
public:
bool insert(int val) {
if (idx.count(val)) return false;
idx[val] = vals.size();
vals.push_back(val);
return true;
}
bool remove(int val) {
auto it = idx.find(val);
if (it == idx.end()) return false;
int i = it->second, last = vals.back();
vals[i] = last; // fill the hole with the last value
idx[last] = i;
vals.pop_back(); // removing the end is O(1)
idx.erase(val); // after idx[last]: val may be last
return true;
}
int getRandom() { return vals[rand() % vals.size()]; }
}; class RandomizedSet {
constructor() { this.vals = []; this.idx = new Map(); } // idx: value -> its index in vals
insert(val) {
if (this.idx.has(val)) return false;
this.idx.set(val, this.vals.length);
this.vals.push(val);
return true;
}
remove(val) {
if (!this.idx.has(val)) return false;
const i = this.idx.get(val), last = this.vals.pop(); // popping the end is O(1)
if (i < this.vals.length) { // fill the hole with the last value
this.vals[i] = last;
this.idx.set(last, i);
}
this.idx.delete(val);
return true;
}
getRandom() { return this.vals[Math.floor(Math.random() * this.vals.length)]; }
} The variations
-
1Swap with the last, then pop
Order in the array does not matter, so move the last element into the removed slot. Every operation touches at most two entries. With duplicates, each value maps to a set of its indexes, and the same swap keeps them correct.
Now you solve -
2A map or array of small facts
Sometimes one number per key is the whole state. A rate limiter stores the next time each message may print. A parking lot keeps three counters in an array indexed by car type.
Now you solve
Mistakes to avoid
- Removing the value from the middle of the array: that shifts everything, O(n).
- Updating the moved value's index in the wrong order when the removed value is itself the last one: it gets re-added to the map.
- With duplicates allowed, mapping each value to one index: map it to a set of indexes instead.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.