Merge k sorted lists
We'll cover the following
Merge three sorted lists into one sorted list.
Watch it run
Press Play or Step to walk through the example, or change the input and press Run. Each frame says what the algorithm does and why.
10
·1
·2
·3
·4
·5
·6
·7
·8
·9
·10
·11
·12
·13
·14
·15
·16
·17
The smallest head is 1, from list 1. Output it and move that list forward. The heap picks this in log k steps.
list heads [4, 2, 3]
1 / 19
The idea
Complexity
| Time | Space | Why |
|---|---|---|
O(N log k) | O(k) | N = all items; the heap holds one head per list. |
In Python
import heapq
def merge_k(lists):
h = [(l[0], i, 0) for i, l in enumerate(lists) if l]
heapq.heapify(h); out = []
while h:
v, i, j = heapq.heappop(h)
out.append(v)
if j + 1 < len(lists[i]):
heapq.heappush(h, (lists[i][j + 1], i, j + 1))
return outSummary: say it in the interview
- Only the front of each list can be the next output. Put those k fronts in a min-heap, pop the smallest, and push the next value from the same list. Cost is log k per output item.
- Time O(N log k), space O(k). N = all items; the heap holds one head per list.