K-Way Merge Interview Pattern: Merging Sorted Lists with a Heap
When an interview problem hands you several sorted inputs and asks for one sorted result, or the kth smallest across all of them, you're looking at the k-way merge interview pattern. The idea is simple: keep the current front element of each input in a min-heap, repeatedly pop the smallest, and push the next element from the same input.
This guide covers when to use it, how to code it, and how to explain it clearly.
Signals that point to k-way merge
- "Merge k sorted lists" or "merge k sorted arrays."
- "Find the kth smallest element in a sorted matrix" where rows or columns are sorted.
- "Find the smallest range that includes at least one number from each list."
- External sorting: data too big for memory, sorted in chunks, then merged.
- Merging sorted logs or event streams from several servers by timestamp.
The common thread: multiple sorted sources and a need to read them in global order.
The core approach
- Push the first element of each non-empty list into a min-heap, along with which list it came from and its index.
- Pop the smallest item and add it to the output.
- If that list has a next element, push it.
- Repeat until the heap is empty.
The heap never holds more than k items, one per list.
Python sketch for merging arrays
import heapq
def merge_k_sorted(lists):
heap = []
for i, lst in enumerate(lists):
if lst:
heapq.heappush(heap, (lst[0], i, 0))
result = []
while heap:
val, i, j = heapq.heappop(heap)
result.append(val)
if j + 1 < len(lists[i]):
heapq.heappush(heap, (lists[i][j + 1], i, j + 1))
return result
Point out why the list index i is in the tuple: when two values tie, Python compares the next field. For linked lists, you'd push (node.val, i, node) so nodes themselves never need to be compared.
Complexity
With N total elements and k lists:
- Time: O(N log k), since each element is pushed and popped once and the heap has at most k items.
- Space: O(k) for the heap, plus the output.
Compare with the naive approaches: concatenating and sorting costs O(N log N), and merging lists one at a time into a growing result can cost O(N·k).
The divide-and-conquer alternative
You can also merge lists in pairs, like the merge step of merge sort: merge list 1 with 2, 3 with 4, and so on, then merge the results. That's also O(N log k) and uses no heap. Mentioning both shows range. A good line: "The heap version streams naturally and works when lists arrive lazily; pairwise merging is nice when I want to avoid heap overhead."
Variant: kth smallest in a sorted matrix
Each row is sorted, so treat each row as a list. Push the first element of each row, then pop k times. The kth pop is the answer. Time is O(k log n) for an n×n matrix. Mention that binary search on the value range is another option for this problem.
Variant: smallest range covering k lists
Keep one element from each list in a min-heap and track the current maximum. The range is from the heap's top to that maximum. Pop the minimum, push the next element from that list, update the maximum, and record the best range. Stop when any list runs out, because you can no longer cover every list.
Variant: merging streams
In system design or practical rounds, you might merge sorted log files from many servers. The same heap idea works with file readers. Mention that only k lines need to be in memory at once, which is why this pattern underpins external sorting.
Edge cases to call out
- Empty input, or some lists empty. Skip empty lists when you initialize.
- k equals 1. The answer is just that list.
- Duplicates across lists, which the heap handles fine.
- Ties in a language that compares whole tuples; add an index to break them.
- Very large k with tiny lists, where pairwise merging may be simpler.
How to explain it in the interview
- Name the brute force and its cost.
- Note that every list is sorted, so the next global smallest is always one of the k front elements.
- Introduce the heap that holds those fronts.
- Code it, then trace a small example: [1, 4], [2, 5], [3].
- State O(N log k) time and O(k) space, and mention the pairwise alternative.
Quick trace
Lists [1, 4], [2, 5], [3]. Heap starts with 1, 2, 3. Pop 1, push 4. Pop 2, push 5. Pop 3. Pop 4. Pop 5. Output: 1, 2, 3, 4, 5. Doing this out loud takes thirty seconds and catches index bugs.
Practice problems
- Merge k sorted lists.
- Kth smallest element in a sorted matrix.
- Smallest range covering elements from k lists.
- Find k pairs with smallest sums.
Make it automatic under pressure
The heap code is short, but tie-breaking, empty lists, and index tracking trip people up when the clock is running. Rehearse it with a timer and narrate each step.
Luna Interview is a practice and calm-under-pressure companion for that, with timed sessions and structured hints in your browser. Try Luna Interview at https://lunainterview.xyz/.
Rehearse with an AI interview copilot, then browse commonly reported interview questions.