Heaps · Pattern 4 of 4

Advanced heaps: two heaps, lazy deletion and best-first search

Heaps combined with other ideas: two heaps that split the data in half for a running median, a frontier that always expands the best candidate next, greedy choices from options you have already passed, and lazy deletion for items that expire.

5 variations · 12 problems · 6 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

  • A running median, or the sum of the smallest k inside a moving window
  • The k smallest pairs or cells, where each answer suggests a few next candidates
  • Decide late: remember every option you have passed and use the best one only when forced
  • Items that change or expire while you need the current max or min

The template

Advanced
// running median: low is a max heap of the smaller half, high a min heap of the larger half
class MedianFinder {
    PriorityQueue<Integer> low = new PriorityQueue<>(Collections.reverseOrder());
    PriorityQueue<Integer> high = new PriorityQueue<>();

    void addNum(int x) {
        low.offer(x);
        high.offer(low.poll());                                 // the largest of low moves up
        if (high.size() > low.size()) low.offer(high.poll());   // low keeps the extra one
    }

    double findMedian() {
        return low.size() > high.size() ? low.peek() : (low.peek() + (double) high.peek()) / 2;
    }
}

// greedy from passed options: refuel at the biggest station only when you must
int minRefuelStops(int target, int startFuel, int[][] stations) {
    PriorityQueue<Integer> passed = new PriorityQueue<>(Collections.reverseOrder());
    long fuel = startFuel;
    int stops = 0, i = 0;
    while (fuel < target) {
        while (i < stations.length && stations[i][0] <= fuel) passed.offer(stations[i++][1]);
        if (passed.isEmpty()) return -1;                        // nothing left to use
        fuel += passed.poll();
        stops++;
    }
    return stops;
}

The variations

  1. 1Two heaps: the middle of the data

    A max heap holds the smaller half and a min heap the larger half, so the median sits on one or both tops. In a sliding window, items also leave: mark them for lazy deletion. Splitting into "the smallest k" and "the rest" the same way keeps a running sum of the k smallest in a window.

  2. 2Best-first frontier

    Start with the obvious best candidate. Each pop is the next answer, and it suggests a few neighbours to push. For pairs, (i, j) leads to (i, j + 1); for the rain-water grid, the lowest boundary cell floods inward first.

  3. 3Greedy from what you have passed

    Sweep in order and push every option you pass. Commit only when you must, and then take the best one in the heap: the biggest fuel station behind you, or the open event that ends soonest.

  4. 4Lazy deletion

    When items expire or change, do not search the heap. Keep the truth in a hash map, and when the top is out of date, pop it and look again. Buildings that ended and corrected stock prices work this way.

  5. 5More practice

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

Mistakes to avoid

  • Two heaps: letting the sizes drift apart by more than one, or forgetting to move an item across so every value in low is ≤ every value in high.
  • Lazy deletion: checking only the top of one heap. Clean the top of every heap you read, and keep a separate count of the valid items.
  • Best-first search: pushing the same candidate twice. Mark cells or index pairs as seen when you push them.
Back to Heaps →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.