Heaps · Pattern 3 of 4
Merge k sorted lists and arrays
Put the first item of every sorted source in a min heap. Pop the smallest, output it, and push the next item from the same source. N items from k sources cost O(N log k).
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
- k sorted lists, arrays, files or feeds to combine into one sorted output
- The smallest range, or the next best item, across several sorted sources
- The most recent items from many users, each user's items already in time order
The template
// heap entries: {value, which list, index in that list}
int[] mergeKSorted(int[][] lists) {
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
int total = 0;
for (int r = 0; r < lists.length; r++) {
total += lists[r].length;
if (lists[r].length > 0) heap.offer(new int[]{lists[r][0], r, 0});
}
int[] res = new int[total];
for (int i = 0; !heap.isEmpty(); i++) {
int[] top = heap.poll();
res[i] = top[0];
int r = top[1], c = top[2] + 1;
if (c < lists[r].length) heap.offer(new int[]{lists[r][c], r, c}); // the next from that list
}
return res;
}
// smallest range with one number from every list: pop the min, track the max
int[] smallestRange(int[][] lists) {
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
int hi = Integer.MIN_VALUE;
for (int r = 0; r < lists.length; r++) {
heap.offer(new int[]{lists[r][0], r, 0});
hi = Math.max(hi, lists[r][0]);
}
int[] best = {heap.peek()[0], hi};
while (true) {
int[] top = heap.poll();
if (hi - top[0] < best[1] - best[0]) best = new int[]{top[0], hi};
int r = top[1], c = top[2] + 1;
if (c == lists[r].length) return best; // a list ran out
heap.offer(new int[]{lists[r][c], r, c});
hi = Math.max(hi, lists[r][c]);
}
} import heapq
def merge_k_sorted(lists): # entries: (value, which list, index)
heap = [(l[0], r, 0) for r, l in enumerate(lists) if l]
heapq.heapify(heap)
res = []
while heap:
v, r, c = heapq.heappop(heap)
res.append(v)
if c + 1 < len(lists[r]):
heapq.heappush(heap, (lists[r][c + 1], r, c + 1)) # the next from that list
return res
def smallest_range(lists): # pop the min, track the max
heap = [(l[0], r, 0) for r, l in enumerate(lists)]
heapq.heapify(heap)
hi = max(l[0] for l in lists)
best = [heap[0][0], hi]
while True:
lo, r, c = heapq.heappop(heap)
if hi - lo < best[1] - best[0]:
best = [lo, hi]
if c + 1 == len(lists[r]):
return best # a list ran out
heapq.heappush(heap, (lists[r][c + 1], r, c + 1))
hi = max(hi, lists[r][c + 1]) // heap entries: {value, which list, index in that list}
using Entry = array<int, 3>;
vector<int> mergeKSorted(vector<vector<int>>& lists) {
priority_queue<Entry, vector<Entry>, greater<Entry>> heap;
for (int r = 0; r < (int)lists.size(); r++)
if (!lists[r].empty()) heap.push({lists[r][0], r, 0});
vector<int> res;
while (!heap.empty()) {
auto [v, r, c] = heap.top(); heap.pop();
res.push_back(v);
if (c + 1 < (int)lists[r].size()) heap.push({lists[r][c + 1], r, c + 1});
}
return res;
}
// smallest range with one number from every list: pop the min, track the max
vector<int> smallestRange(vector<vector<int>>& lists) {
priority_queue<Entry, vector<Entry>, greater<Entry>> heap;
int hi = INT_MIN;
for (int r = 0; r < (int)lists.size(); r++) {
heap.push({lists[r][0], r, 0});
hi = max(hi, lists[r][0]);
}
vector<int> best = {heap.top()[0], hi};
while (true) {
auto [lo, r, c] = heap.top(); heap.pop();
if (hi - lo < best[1] - best[0]) best = {lo, hi};
if (c + 1 == (int)lists[r].size()) return best; // a list ran out
heap.push({lists[r][c + 1], r, c + 1});
hi = max(hi, lists[r][c + 1]);
}
} // 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;
}
}
// heap entries: [value, which list, index in that list]
function mergeKSorted(lists) {
const heap = new MinHeap((a, b) => a[0] < b[0]);
lists.forEach((l, r) => { if (l.length) heap.push([l[0], r, 0]); });
const res = [];
while (heap.size) {
const [v, r, c] = heap.pop();
res.push(v);
if (c + 1 < lists[r].length) heap.push([lists[r][c + 1], r, c + 1]); // the next from that list
}
return res;
}
// smallest range with one number from every list: pop the min, track the max
function smallestRange(lists) {
const heap = new MinHeap((a, b) => a[0] < b[0]);
let hi = -Infinity;
lists.forEach((l, r) => { heap.push([l[0], r, 0]); hi = Math.max(hi, l[0]); });
let best = [heap.peek()[0], hi];
for (;;) {
const [lo, r, c] = heap.pop();
if (hi - lo < best[1] - best[0]) best = [lo, hi];
if (c + 1 === lists[r].length) return best; // a list ran out
heap.push([lists[r][c + 1], r, c + 1]);
hi = Math.max(hi, lists[r][c + 1]);
}
} The variations
-
1Merge k sorted sources
The heap holds one candidate per source: the value plus where it came from. Pop, output, push that source's next item. With linked lists the node itself knows its next, so store the node.
Now you solve -
2Pop the min, track the max
Keep exactly one number from every list. The heap gives the minimum, and a plain variable remembers the maximum. Moving the minimum forward is the only way the range can shrink; stop when any list runs out.
-
3Merging inside a design
A news feed is a merge of each followed user's posts, newest first. Push each user's latest post, pop the newest, push that user's previous post, and stop after 10.
Mistakes to avoid
- Pushing every item of every list at the start: it works, but costs O(N log N) instead of O(N log k).
- Forgetting to push the next item from the same source after a pop, so a list stops after its first item.
- Pushing empty lists (or null list heads) into the heap.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.