Courses / DSA Patterns for Working Engineers / Chapter 8
Module 3 · Heaps, k-way merges and top k · Chapter 8 of 39
K-Way Merge: Combining Sorted Streams With a Heap
Builds on Two Pointers: Pairs, Partitions and In-Place Scans, Fast and Slow Pointers: Cycles, Midpoints and Repeats and Heaps and Two Heaps: Running Medians and Priority Scheduling. Next up: Top K Elements: Size-K Heaps, Buckets and Quickselect.
Part 1 · Introduction to k-way merge
From two lists to k lists
Logs from several servers, results from several exam centres and price lists from several shops often arrive already sorted, one list per source. Merging them into one sorted list is the job of a k-way merge, and it needs a heap to stay fast when there are many sources.
Merging two sorted lists is the two pointers idea from the chapter of that name. Keep one index in each list, compare the two items they point at, copy the smaller one to the output and advance that index. When one list is used up, copy the rest of the other. Each output item costs at most one comparison, so merging lists of total length N costs O(N).
// Merge two sorted arrays into one sorted array with two pointers. export function mergeTwo(a: number[], b: number[]): number[] { const out: number[] = [] let i = 0 let j = 0 while (i < a.length && j < b.length) { if (b[j] < a[i]) out.push(b[j++]) else out.push(a[i++]) // on a tie, take from a first } while (i < a.length) out.push(a[i++]) while (j < b.length) out.push(b[j++]) return out }
Merge two sorted arrays with two pointers
Now take k lists. One option is to merge them two at a time, but if you merge the first list into the second, then the result into the third, the early items are copied again at every step, and the cost can grow toward k times N. The better observation is that the next item of the merged output is always the smallest of the current heads, the first unused item of each list. With k lists you need the smallest of k values, and then to replace it by the next item from the same list. That is a job for a min-heap.