One head per list
You have K already-sorted lists and want one merged sorted output. The naive concat-then-sort is O(N log N) and throws away the fact that each list is sorted. The heap way keeps only K candidates at a time: the current front of each list.
A min-heap of those K heads always exposes the global smallest. Pop it, append to the output, then push the next element from whichever list it came from. Repeat until the heap drains. Only K items live in the heap at once, so each of the N pops costs O(log K).
for i in 0..K: heap.push(list[i][0], i, 0)
while heap:
(v, i, j) = heap.pop() # global min
out.append(v)
if j+1 < len(list[i]):
heap.push(list[i][j+1], i, j+1)
N total elements, each pushed and popped once from a heap of size ≤ K.
The heap holds at most one head per list, so K entries.
Step-by-step trace
| # | Action | Popped | From | Pushed next | Heap (val·list) | Output |
|---|