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.
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
// 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;
} import heapq
class MedianFinder: # low: max heap (negatives), high: min heap
def __init__(self):
self.low, self.high = [], []
def add_num(self, x):
heapq.heappush(self.low, -x)
heapq.heappush(self.high, -heapq.heappop(self.low)) # the largest of low moves up
if len(self.high) > len(self.low):
heapq.heappush(self.low, -heapq.heappop(self.high)) # low keeps the extra one
def find_median(self):
if len(self.low) > len(self.high):
return -self.low[0]
return (-self.low[0] + self.high[0]) / 2
def min_refuel_stops(target, start_fuel, stations): # refuel only when you must
passed, fuel, stops, i = [], start_fuel, 0, 0
while fuel < target:
while i < len(stations) and stations[i][0] <= fuel:
heapq.heappush(passed, -stations[i][1])
i += 1
if not passed:
return -1 # nothing left to use
fuel -= heapq.heappop(passed)
stops += 1
return stops // running median: low is a max heap of the smaller half, high a min heap of the larger half
class MedianFinder {
priority_queue<int> low;
priority_queue<int, vector<int>, greater<int>> high;
public:
void addNum(int x) {
low.push(x);
high.push(low.top()); low.pop(); // the largest of low moves up
if (high.size() > low.size()) { low.push(high.top()); high.pop(); }
}
double findMedian() {
return low.size() > high.size() ? low.top() : (low.top() + (double)high.top()) / 2;
}
};
// greedy from passed options: refuel at the biggest station only when you must
int minRefuelStops(int target, int startFuel, vector<vector<int>>& stations) {
priority_queue<int> passed;
long long fuel = startFuel;
int stops = 0, i = 0;
while (fuel < target) {
while (i < (int)stations.size() && stations[i][0] <= fuel) passed.push(stations[i++][1]);
if (passed.empty()) return -1; // nothing left to use
fuel += passed.top(); passed.pop();
stops++;
}
return stops;
} // a binary heap; less(a, b) is true when a should come out first
class MinHeap {
constructor(less = (a, b) => a < b) { this.a = []; this.less = less; }
get size() { return this.a.length; }
peek() { return this.a[0]; }
push(x) {
const a = this.a; a.push(x);
for (let i = a.length - 1; i > 0;) { // sift up
const p = (i - 1) >> 1;
if (!this.less(a[i], a[p])) break;
[a[i], a[p]] = [a[p], a[i]]; i = p;
}
}
pop() {
const a = this.a, top = a[0], last = a.pop();
if (a.length) {
a[0] = last;
for (let i = 0; ;) { // sift down
const l = 2 * i + 1, r = l + 1; let m = i;
if (l < a.length && this.less(a[l], a[m])) m = l;
if (r < a.length && this.less(a[r], a[m])) m = r;
if (m === i) break;
[a[i], a[m]] = [a[m], a[i]]; i = m;
}
}
return top;
}
}
// running median: low is a max heap of the smaller half, high a min heap of the larger half
class MedianFinder {
constructor() { this.low = new MinHeap((a, b) => a > b); this.high = new MinHeap(); }
addNum(x) {
this.low.push(x);
this.high.push(this.low.pop()); // the largest of low moves up
if (this.high.size > this.low.size) this.low.push(this.high.pop());
}
findMedian() {
return this.low.size > this.high.size ? this.low.peek() : (this.low.peek() + this.high.peek()) / 2;
}
}
// greedy from passed options: refuel at the biggest station only when you must
function minRefuelStops(target, startFuel, stations) {
const passed = new MinHeap((a, b) => a > b);
let fuel = startFuel, stops = 0, i = 0;
while (fuel < target) {
while (i < stations.length && stations[i][0] <= fuel) passed.push(stations[i++][1]);
if (!passed.size) return -1; // nothing left to use
fuel += passed.pop();
stops++;
}
return stops;
} The variations
-
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.
-
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.
Now you solve -
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.
Now you solve -
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.
Now you solve -
5More practice
More problems that use this pattern. Try them once the variations above feel easy.
Problems
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
lowis ≤ every value inhigh. - 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.
Lesson done
Back to Heaps →Mark it done once you can write the template from memory and you have solved the worked examples yourself.