Design Data Structures · Pattern 6 of 10
Hash map + heap: expiring keys in time order
The map holds the current value and expiry of each key; a min-heap holds expiry times, so the next key to expire is always on top. Before each call, pop everything that has expired.
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
- Keys expire after a duration
- Count only the items that are still alive
- Something must happen to the earliest (or smallest) item first
The template
class TimeLimitedCache {
Map<Integer, int[]> map = new HashMap<>(); // key -> {value, expiresAt}
PriorityQueue<int[]> heap = new PriorityQueue<>((x, y) -> Integer.compare(x[0], y[0])); // {expiresAt, key}
void purge(int now) { // drop what has expired
while (!heap.isEmpty() && heap.peek()[0] <= now) {
int[] e = heap.poll();
int[] cur = map.get(e[1]);
if (cur != null && cur[1] == e[0]) map.remove(e[1]); // skip stale heap entries
}
}
boolean set(int now, int key, int value, int duration) {
purge(now);
boolean alive = map.containsKey(key);
map.put(key, new int[]{value, now + duration});
heap.offer(new int[]{now + duration, key});
return alive;
}
int get(int now, int key) {
purge(now);
int[] cur = map.get(key);
return cur == null ? -1 : cur[0];
}
int count(int now) { purge(now); return map.size(); }
} import heapq
class TimeLimitedCache:
def __init__(self):
self.map = {} # key -> (value, expires_at)
self.heap = [] # (expires_at, key)
def _purge(self, now): # drop what has expired
while self.heap and self.heap[0][0] <= now:
t, key = heapq.heappop(self.heap)
if key in self.map and self.map[key][1] == t: # skip stale heap entries
del self.map[key]
def set(self, now, key, value, duration):
self._purge(now)
alive = key in self.map
self.map[key] = (value, now + duration)
heapq.heappush(self.heap, (now + duration, key))
return alive
def get(self, now, key):
self._purge(now)
return self.map[key][0] if key in self.map else -1
def count(self, now):
self._purge(now)
return len(self.map) class TimeLimitedCache {
unordered_map<int, pair<int, int>> mp; // key -> {value, expiresAt}
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> heap; // {expiresAt, key}
void purge(int now) { // drop what has expired
while (!heap.empty() && heap.top().first <= now) {
auto [t, key] = heap.top(); heap.pop();
auto it = mp.find(key);
if (it != mp.end() && it->second.second == t) mp.erase(it); // skip stale heap entries
}
}
public:
bool set(int now, int key, int value, int duration) {
purge(now);
bool alive = mp.count(key);
mp[key] = {value, now + duration};
heap.push({now + duration, key});
return alive;
}
int get(int now, int key) {
purge(now);
auto it = mp.find(key);
return it == mp.end() ? -1 : it->second.first;
}
int count(int now) { purge(now); return mp.size(); }
}; class TimeLimitedCache {
constructor() { this.map = new Map(); this.heap = []; } // key -> [value, expiresAt]; heap of [expiresAt, key]
push(e) { // JS has no heap: sift the new entry up
const h = this.heap; h.push(e);
for (let i = h.length - 1, p; i > 0 && h[p = (i - 1) >> 1][0] > h[i][0]; i = p) [h[p], h[i]] = [h[i], h[p]];
}
pop() { // take the top, sift the last entry down
const h = this.heap, top = h[0], last = h.pop();
if (h.length) {
h[0] = last;
for (let i = 0; ; ) {
let m = i;
for (const c of [2 * i + 1, 2 * i + 2]) if (c < h.length && h[c][0] < h[m][0]) m = c;
if (m === i) break;
[h[m], h[i]] = [h[i], h[m]]; i = m;
}
}
return top;
}
purge(now) { // drop what has expired
while (this.heap.length && this.heap[0][0] <= now) {
const [t, key] = this.pop(), cur = this.map.get(key);
if (cur && cur[1] === t) this.map.delete(key); // skip stale heap entries
}
}
set(now, key, value, duration) {
this.purge(now);
const alive = this.map.has(key);
this.map.set(key, [value, now + duration]);
this.push([now + duration, key]);
return alive;
}
get(now, key) { this.purge(now); return this.map.has(key) ? this.map.get(key)[0] : -1; }
count(now) { this.purge(now); return this.map.size; }
} The variations
-
1Expire with a min-heap and lazy deletion
Never search the heap to update a key. Push a new
(expiresAt, key)entry and let the old one become stale; when it pops, the map shows a different expiry, so it is ignored. In JavaScript you can also give each key its ownsetTimeout, but a heap works the same in every language and with a clock you control. -
2More practice
More problems that use this pattern. Try them once the variations above feel easy.
Problems
Mistakes to avoid
- Removing a key when an old heap entry pops, even though the key was set again later with a new expiry: compare the expiry times first.
- Off by one on expiry: a key set at 0 for 100 is gone at time 100, so purge with
<= now. - Counting with
map.size()before purging expired keys.
Lesson done
Next: Randomized algorithms: a fair shuffle →Mark it done once you can write the template from memory and you have solved the worked examples yourself.