04
Design with hash maps (Arrays & Hashing Sub-pattern)
Build a class where every operation is O(1). A hash map alone can find things, but can't keep an order or pick a random element — so pair it with a list or array that can.
Signals in the problem statement
- ›
"design a data structure"
- ›
"each operation in O(1) average time"
- ›
"least recently used", "least frequently used"
- ›
"get a random element"
What makes it different
Think in invariants: "the map always points at the right node", "the list is ordered most → least recent". Every operation must keep both structures in sync.
Questions
ordered from “learn the idea” to “recognise it without help”- 1Insert Delete GetRandom O(1)WalkthroughMediumBasic Anchor·LeetCode #380
- 2LRU CacheWalkthroughMediumMedium·LeetCode #146
- 3LFU CacheWalkthroughHardTricky / Edge Case·LeetCode #460
Template
design-template.cpp
// LRU-style cache: the map finds a key in O(1), the list keeps recency order.
class Cache {
int capacity;
list<pair<int, int>> order; // front = most recent
unordered_map<int, list<pair<int, int>>::iterator> where; // key -> its node in the list
public:
Cache(int capacity) : capacity(capacity) {}
int get(int key) {
auto it = where.find(key);
if (it == where.end()) return -1;
order.splice(order.begin(), order, it->second); // move to front, O(1)
return it->second->second;
}
void put(int key, int value) {
auto it = where.find(key);
if (it != where.end()) { // existing key: update + move to front
it->second->second = value;
order.splice(order.begin(), order, it->second);
return;
}
if ((int)order.size() == capacity) { // full: evict the least recent
where.erase(order.back().first);
order.pop_back();
}
order.emplace_front(key, value);
where[key] = order.begin();
}
};Remember this · Arrays & Hashing
Trigger
"Have I seen X before?", pairs that add up to a target, grouping things that look alike, counting occurrences.
Think
Instead of scanning again for each element, can I remember earlier elements in a map?
Key question
What exactly do I store as the key, and what as the value?