Learn the pattern · ~15 min
K-way Merge
also called heap frontier, lazy expansion
Merge k sorted sources with a min-heap of their fronts: pop the smallest, then push the next element from the same source.
Reach for it when you read
- +k sorted lists, arrays or rows, and you need their values in order: merged, the k-th, or the first few.
- +A sorted matrix (rows and columns sorted) and the k-th smallest value.
- +Pairs or sums whose order you can generate one step at a time: (i, j) is followed by (i, j + 1).
- +Numbers built from earlier answers in increasing order (ugly numbers).
- +A range that must hold one value from every list.
Not this one when
- ×Only two sorted lists: two pointers, no heap.
- ×One unsorted array and the k-th smallest: quickselect or a single heap of size k.
- ×Merging overlapping intervals: sort by start and sweep.
Learn K-way Merge
First, what does "merge" mean here?
To merge two sorted lists is to combine them into one sorted list, without sorting again. [2, 6, 9] and [1, 7] merge into [1, 2, 6, 7, 9]. It's the last step of merge sort.
K-way merge is the same job with k sorted lists instead of two.
The word that matters is sorted. Because each list is sorted, its front (the first element not taken yet) is the smallest thing left in it. So the next value of the answer is always one of the fronts.
How do we merge two lists?
Take [2, 6, 9] and [1, 7]. Keep one pointer on each front. The rule is one line:
Compare the two fronts, take the smaller one, and move only that list's pointer.
| step | fronts | what happens | output so far |
|---|---|---|---|
| 1 | 2, 1 | 1 is smaller: take it, the second list moves to 7 | 1 |
| 2 | 2, 7 | 2 is smaller: take it, the first list moves to 6 | 1, 2 |
| 3 | 6, 7 | 6 is smaller: take it, the first list moves to 9 | 1, 2, 6 |
| 4 | 9, 7 | 7 is smaller: take it, the second list is now empty | 1, 2, 6, 7 |
| 5 | 9, none | only one list left: take 9 | 1, 2, 6, 7, 9 |
Every step takes exactly one value, so two lists of total length N take N steps.
The code for it
while (i < a.size() || j < b.size()) {
if (j == b.size() || (i < a.size() && a[i] <= b[j]))
out.push_back(a[i++]); // a's front is smaller (or b is empty)
else
out.push_back(b[j++]); // take b's front, move only j
}You don't need to memorise this. It's the table: compare the fronts, take the smaller, move that pointer.
Why is it safe to look only at the fronts? Because behind each front sits nothing smaller: in [2, 6, 9], 6 and 9 can't come before 2. So the smaller front is the smallest value left anywhere.
Why <= and not <? On a tie, take from the first list. Either choice gives a sorted output; <= also keeps equal values in their original order.
Fine, but how does this help us?
The classic problem: Merge k Sorted Lists. You get k sorted linked lists; return one sorted list with all their nodes.
Merge [2, 6, 9], [1, 7] and [3, 4, 10]. By hand, keep a finger on each front and take the smallest each time:
| step | fronts | how you find the next value | take |
|---|---|---|---|
| 1 | 2, 1, 3 | smallest of three fronts | 1 |
| 2 | 2, 7, 3 | smallest of three | 2 |
| 3 | 6, 7, 3 | smallest of three | 3 |
| 4 | 6, 7, 4 | smallest of three | 4 |
| 5 | 6, 7, 10 | smallest of three | 6 |
| 6 | 9, 7, 10 | smallest of three | 7 |
| 7 | 9, none, 10 | the second list is empty | 9 |
| 8 | none, none, 10 | only one front left | 10 |
The answer is 1, 2, 3, 4, 6, 7, 9, 10.
The brute force
Before every output, scan all k fronts for the smallest.
ListNode* mergeBrute(vector<ListNode*> lists) {
ListNode dummy, *tail = &dummy;
while (true) {
int best = -1;
for (int i = 0; i < (int)lists.size(); i++) // scan all k fronts
if (lists[i] && (best == -1 || lists[i]->val < lists[best]->val)) best = i;
if (best == -1) break; // every list is empty
tail->next = lists[best]; tail = tail->next;
lists[best] = lists[best]->next;
}
return dummy.next;
}It's correct, but each of the N outputs scans k fronts: O(N · k). LeetCode keeps N ≤ 10⁴, so there it passes. But at N = 10⁶ nodes over k = 10⁴ lists it's 10¹⁰ comparisons: we measured 4.3 seconds. Time limit exceeded.
(Copying every value into one array and sorting also works, in O(N log N), but it ignores that the lists were already sorted.)
The one thought that fixes it
Stop at step 4. The fronts are 6, 7, 4. One step earlier they were 6, 7, 3.
Only one front changed: the 3 was taken, so its list moved to 4. The 6 and the 7 are the same as before, and we already compared them. Scanning them again tells us nothing new.
After every take, exactly one front changes: the next node of the list we just took from. So we need a box that holds the k fronts and can:
- tell us the smallest one, fast;
- take it out, and put one new value in, fast.
That's a min-heap of fronts. Its top is the smallest front, a pop removes it, a push adds its successor. Each costs O(log k) instead of a k-long scan, because the heap holds at most one front per list.
ListNode* mergeKLists(vector<ListNode*>& lists) {
auto cmp = [](ListNode* a, ListNode* b) { return a->val > b->val; }; // > makes a min-heap
priority_queue<ListNode*, vector<ListNode*>, decltype(cmp)> heap(cmp);
for (ListNode* head : lists)
if (head) heap.push(head); // the k fronts; skip empty lists
ListNode dummy;
ListNode* tail = &dummy;
while (!heap.empty()) {
ListNode* node = heap.top(); heap.pop(); // the smallest front
tail->next = node; tail = node;
if (node->next) heap.push(node->next); // only this list's front changed
}
return dummy.next;
}Dry run
Same three lists. The heap is listed sorted, though inside it isn't.
| heap (fronts) | pop | push (its next node) | output so far |
|---|---|---|---|
| 1, 2, 3 | 1 | 7 | 1 |
| 2, 3, 7 | 2 | 6 | 1, 2 |
| 3, 6, 7 | 3 | 4 | 1, 2, 3 |
| 4, 6, 7 | 4 | 10 | 1, 2, 3, 4 |
| 6, 7, 10 | 6 | 9 | 1, 2, 3, 4, 6 |
| 7, 9, 10 | 7 | none, list ended | 1, 2, 3, 4, 6, 7 |
| 9, 10 | 9 | none | …, 7, 9 |
| 10 | 10 | none | …, 9, 10 |
1, 2, 3, 4, 6, 7, 9, 10, the same answer as the brute force.
Why it's O(N log k)
Count what happens to each node: it's pushed once and popped once, and with at most k nodes in the heap each costs O(log k). That's O(N log k) time. For N = 10⁶ and k = 10⁴, about 3 × 10⁷ steps instead of 10¹⁰: it ran in 0.03 seconds. The heap holds at most k pointers: O(k) extra space.
From O(N · k) to O(N log k), by never comparing two fronts we've already compared.
The k-th smallest? Stop counting at k
The k-th smallest value in a matrix whose rows are sorted: each row is a list. A front must now say where it came from, so store {value, row, index}, and stop at the k-th pop:
auto [v, li, id] = heap.top(); heap.pop();
if (--k == 0) return v; // the k-th pop is the answer
if (id + 1 < (int)L[li].size()) heap.push({L[li][id + 1], li, id + 1});On our three lists, the 5th smallest is 6: the pops go 1, 2, 3, 4, 6.
One value from every list? Track the max too
Smallest Range Covering Elements from K Lists: find the shortest range [a, b] that holds at least one value of every list. The fronts hold one value per list and span [smallest front, largest front]; keep the largest in mx. Only moving the smallest front forward can shrink the range, and once a list runs out you stop:
auto [v, li, id] = heap.top(); heap.pop(); // v is the smallest front
if (mx - v < best[1] - best[0]) best = {v, mx}; // fronts span [v, mx]
if (id + 1 == (int)L[li].size()) break; // a list ran out: stop
heap.push({L[li][id + 1], li, id + 1});
mx = max(mx, L[li][id + 1]);On [4, 10, 15, 24, 26], [0, 9, 12, 20], [5, 18, 22, 30] it starts at [0, 5] and ends with [20, 24]. The < keeps the earlier range on a tie in width.
Remember this
- Only the fronts can be next, because every list is sorted. Keep them in a min-heap.
- After a pop, push only the successor of what you popped, never a whole list.
- Store where each front came from (the node, or
{value, list, index}), or you can't find its successor. - Skip empty lists: an empty list has no front.
- Whenever a problem gives you "k sorted sources and asks for their values in order" (merged, the k-th, the first few), it's a k-way merge.
Practise it on Merge Two Sorted Lists, then Merge k Sorted Lists, Kth Smallest Element in a Sorted Matrix (stop at the k-th), Find K Pairs with Smallest Sums (imagined lists: pair (i, j) is followed by (i, j + 1)), Ugly Number II (lists built from the answer itself) and Smallest Range Covering Elements from K Lists.
Below, watch Merge k Sorted Lists run line by line.
Watch it work, line by line
Merge k Sorted Lists ↗, A = [1, 2, 9], B = [4, 5], C = [3, 7] → [1, 2, 3, 4, 5, 7, 9]. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 4 times it stops to ask you what happens next.
When to use it, and when not
Ask yourself
Am I combining several sources that are each already sorted (lists, rows, or sequences I can generate in order), where the next answer must be at the front of one of them?
Reach for it when
- +k sorted lists/arrays/rows
- +k-th smallest across sorted structures
- +generate a sorted stream from several generators (ugly numbers)
- +total N items, k sources -> O(N log k)
It fails when
- ×Only two sorted listsuse Two-pointer merge, O(n), no heap
- ×Sources aren't sorted; sorting them first may dominateuse Rethink the approach
- ×Just the k-th value with a monotone count (sorted matrix, multiplication table)use Binary search on the answer, O(n log range)
- ×k-th in a single unsorted arrayuse Quickselect
- ×You reach for concatenate-and-sort: O(N log N), ignores order, needs all N in memory, fails on streamsuse Size-k heap, O(N log k)
Looks like it, isn't (and the other way round)
- Find the K-Sum of an Array looks like Subsets / Permutations / Combinations, needs this pattern
Enumerating subsets is 2n. Sort |a| and pop k times from a frontier heap with the 'extend / replace last' successor rule.
- Median of Two Sorted Arrays looks like K-way Merge, needs Binary Search
Merging is O(m + n); binary searching the partition is O(log min(m, n)).
- Kth Smallest Element in a Sorted Matrix looks like K-way Merge, needs Binary Search on the Answer
Heap works, but binary search on the value with a staircase count is often better.
Why this pattern and not another
Inputs are already sorted and you want a globally sorted merge or the k-th element. A size-k min-heap exploits the per-list sortedness to emit elements in order at O(log k) each — never re-sorting.
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1What does the heap hold at every moment?Reveal
Exactly one entry per non-empty source: its smallest unused element. So the heap's top is the next element overall.
2After popping a value, what do you push?Reveal
The next element from the same source, if it has one. Nothing else.
3What's the cost, and why is it better than sorting everything?Reveal
O(N log k) with an O(k) heap, versus O(N log N). It uses the order you were given and works on streams.
4Why can the heap hold just one entry per list?Reveal
Each list is sorted, so anything behind a list's front is at least as big as that front. The next output is always some front, so the rest never needs to be looked at yet.
Practice ladder
- 1Merge Two Sorted Liststwo sourcesEasy
- 2Merge Sorted Arraytwo sources, in placeEasy
- 3Kth Smallest Element in a Sorted Matrixstop at the k-thMedium
- 4Find K Pairs with Smallest Sumsimagined sourcesMedium
- 5Ugly Number IIbuilt from the outputMedium
- 6Merge k Sorted Liststhe hookHard
- 7Super Ugly Numberbuilt from the outputMedium
- 8Smallest Range Covering Elements from K Listsone from every sourceHard
Finished K-way Merge? Mark it done and Lessgo moves you to the next step.