K-way Merge
One min-heap as a frontier across k sorted lists. Push the smallest from each list. Pop the global min, push its successor. Heap size stays at k. O(N log k) — every element placed exactly once.
Sequential merge = O(kN) — early lists merged k times. Min-heap frontier = O(N log k) — each element placed exactly once.
The insight: you only ever need to compare k candidates at once — the current front of each list. A min-heap of size k always gives you the global minimum in O(log k). Pop it, push the next element from the same list, repeat. Total: N pops × O(log k) each = O(N log k).
The Heap Tuple: (value, list_idx, elem_idx)
The three-part tuple is the entire design of this pattern.
valuelist_idxelem_idxFor sorted matrix: use (value, row, col) — advancing right = col+1 in same row
Tie-breaking: when values are equal, Python compares list_idx next — always include list_idx to avoid TypeError on equal values
The 3-Step Framework
Three steps, all problems use the same loop.
Initialize the heap with one (value, list_idx, elem_idx) tuple per list. Only push if the list is non-empty. This creates a frontier of k candidates — the current minimum of each list.
for i, lst in enumerate(lists):
if lst:
heapq.heappush(heap, (lst[0], i, 0))
# Heap size = k (or fewer if some lists empty)While heap is not empty: pop (val, list_i, elem_i) — this is the globally smallest remaining element. Add val to result (or count toward kth). Push the next element from the same list: (lists[list_i][elem_i+1], list_i, elem_i+1).
while heap:
val, li, ei = heapq.heappop(heap)
result.append(val)
if ei + 1 < len(lists[li]):
heapq.heappush(heap,
(lists[li][ei+1], li, ei+1))For 'kth smallest' problems, don't collect all results — just count pops. When count reaches k, return the current val. Same loop, different termination condition. The heap does all the work of finding the global order.
count = 0
while heap:
val, li, ei = heapq.heappop(heap)
count += 1
if count == k: return val # done!
if ei+1 < len(lists[li]):
heapq.heappush(heap, (lists[li][ei+1], li, ei+1))Pattern Recognition
'k sorted lists/arrays' → this pattern immediately.