Combine K Sorted Sequences into One
Heaps, Sorting & SearchAuto-graded · 21 test casesLast updated
Tests whether a candidate can use a min-heap to efficiently merge multiple sorted lists into a single sorted output in O(N log k) time.
Problem
You have k sequences of integers, each one already sorted in non-decreasing order. Your job is to combine all of them into one sorted sequence containing every element across all inputs.
A brute-force approach — scanning the front of every sequence at each step to find the next smallest value — becomes unacceptably slow as k grows large. Your solution must do better.
Task
Given a list of k sorted integer lists, return a single list with all elements in non-decreasing order.
Constraints
1 <= k <= 10^5- Each individual list may be empty or contain any number of elements.
- The total number of elements
Nacross all lists satisfies0 <= N <= 10^6. - All integer values fit in a 32-bit signed range.
- Your solution must run in O(k + N log k) time. An O(N·k) solution is not acceptable.
Examples
Example 1
Input: combine_sorted_lists([[1, 4, 9], [2, 6], [0, 3, 7, 8]])
Output: [0, 1, 2, 3, 4, 6, 7, 8, 9]
Hints
Hint 1
At any moment, the next element of the merged output must be the minimum among the current front elements of all lists. What data structure retrieves and replaces a minimum in O(log k) rather than O(k)?
Hint 2
Store a tuple of (value, list_index, position_within_list) in the heap. The list_index and position let you locate and enqueue the successor element after a pop — without those two pieces, you have no way to know where to look next.
Hint 3
Seed the heap once using heapify, which costs O(k). Then every element is pushed and popped exactly once, each costing O(log k), giving O(k + N log k) overall. Watch out for empty input lists: attempting to read index 0 of an empty list will crash.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core observation is that the next element of the merged output is always the smallest front element among all input lists. Each list is sorted, so its first unconsumed element is its local minimum. Finding the global minimum naively costs O(k) per step, which degrades to O(N·k) overall — too slow when both N and k are large.
A min-heap solves this. It holds at most one "frontier" entry per list: the smallest unconsumed element of that list. Retrieving the minimum costs O(1), and replacing it with the next element from the same list costs O(log k), because the heap never grows larger than k.
Algorithm
- Seed: iterate over all k lists. For each non-empty list, add a tuple
(value, list_index, position)to a staging list, then callheapifyonce. This costs O(k) — cheaper than k individual pushes. - Loop: while the heap is non-empty, pop the minimum tuple. Append its value to the result. If the same list still has elements remaining, push the next one.
- Terminate: the heap empties when every element has been consumed. Return the result.
Why it is correct
Before each pop, the heap contains the smallest unconsumed element of every list that still has elements — nothing more, nothing less. This invariant holds initially by construction (we seed with index 0 of each list). It is maintained because popping from list i at position j leaves position j+1 as the new frontier for that list, and we push exactly that. Any unconsumed element is at least as large as its own list's frontier, and the popped value is the smallest frontier, so the output is globally non-decreasing.
Each element is pushed exactly once and popped exactly once, so all N elements appear in the output and the loop terminates.
Tie-breaking: when two heap entries share the same value, Python compares the second field (list_index). Since no two entries share a list_index, ties are always resolved without reaching a non-comparable third field. Equal values may appear in any relative order in the output, which is correct because they are indistinguishable integers.
Edge cases
- All lists empty / N = 0: the heap is seeded with nothing and the function returns
[]immediately. - Some lists empty: the seeding loop skips them; they are never touched again.
- k = 1: the heap holds one entry at a time and the output equals the input list.
- Duplicates within or across lists: handled naturally by the tuple comparison described above.
- Highly unbalanced lengths: correctness is unaffected; the heap shrinks as shorter lists are exhausted.
Complexity
- Time: O(k + N log k).
heapifyis O(k). Each of the N elements is pushed once and popped once, each operation costing O(log k) on a heap of size ≤ k. - Space: O(k) auxiliary for the heap, plus O(N) for the output (unavoidable).
This is asymptotically optimal for comparison-based merging: the number of distinct interleavings of k sorted arrays requires Ω(N log k) comparisons to distinguish.
Alternative approaches
- Divide-and-conquer pairwise merging (merge pairs of lists, then pairs of results) is also O(N log k) and avoids an explicit heap.
- Concatenate and sort is O(N log N), which is worse than O(N log k) whenever k ≪ N, and it throws away all existing sortedness.
- Sequential merging (merge list 1 with 2, result with 3, and so on) degrades to O(N·k) in the worst case.
import heapq
from typing import List
def combine_sorted_lists(lists: List[List[int]]) -> List[int]:
# Build the initial heap from the first element of each non-empty list.
# Each entry is (value, list_index, position) so we can find the successor.
heap = []
for list_index, lst in enumerate(lists):
if lst:
heap.append((lst[0], list_index, 0))
heapq.heapify(heap) # O(k) — cheaper than k individual pushes
result = []
while heap:
value, list_index, pos = heapq.heappop(heap)
result.append(value)
# If this list has a next element, push it to maintain the frontier.
next_pos = pos + 1
if next_pos < len(lists[list_index]):
heapq.heappush(heap, (lists[list_index][next_pos], list_index, next_pos))
return result