Heap · Stage 3 of 3
K-Way Merge
Hold one head per sorted list; the heap's top is always the next output
Foundations
So far, the heap chose among items it held all at once. Now, what if the items arrive as several sorted lists, and you need one sorted output without collecting everything first?
Every list is sorted, so the smallest value not yet merged is one of the lists' current heads. Keep a min-heap of exactly one head per list. Pop the top, append it to the output, and push the next value from the same list. With k lists the heap never holds more than k items, so each of the N values costs O(log k).
Split nums = [7, 1, 5, 3, 6] into two runs and sort each: [1, 5, 7] and [3, 6]. The heap starts with heads 1 and 3. Popping 1 brings in 5; popping 3 brings in 6; then 5, 6, and 7 follow. The output is [1, 3, 5, 6, 7], and the heap held two items the whole time, one per run.
nums
run 0, sorted
run 1, sorted
merged
- Open lesson
Sentinel (Dummy) Head & Merging
Merging two lists picks the smaller head. Merging
klists does the same with a heap choosing amongkheads.
Case Scenario
The problem
Merge k Sorted Lists
You are given an array of k linked lists lists, each sorted in ascending order. Merge all of them into one sorted linked list and return it.
- Input
- lists = [[1, 4, 5], [1, 3, 4], [2, 6]]
- Output
- [1, 1, 2, 3, 4, 4, 5, 6]
Merge k Sorted Lists gives k sorted linked lists and asks for one sorted list. The heap holds each list's current head node, keyed by its value, so the next node to attach is always on top. For lists = [[1, 4, 5], [1, 3, 4], [2, 6]], the merged list is [1, 1, 2, 3, 4, 4, 5, 6].
The direct approach copies every value into one list, sorts it, and builds a new linked list. That costs O(N log N) for N nodes in total and throws away the order each list already had, treating the inputs as if they were random.
Pro
The rest of this is on Pro
The idea above is free. The walkthrough, the cost, and the practice are on Pro.