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.

2 variations · 2 problems · 1 with animated walkthroughs

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

Hash Map + Heap
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(); }
}

The variations

  1. 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 own setTimeout, but a heap works the same in every language and with a clock you control.

  2. 2More practice

    More problems that use this pattern. Try them once the variations above feel easy.

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