Combine Multiple Sorted Lists into a Single Sorted Sequence
Heaps, Sorting & SearchAuto-graded · 19 test casesLast updated
Tests divide-and-conquer merging and two-pointer techniques to efficiently combine many pre-sorted lists.
You receive a collection of integer lists, where every individual list is already arranged in non-decreasing order. Your task is to produce one list containing all the integers from every input list, preserving every duplicate and maintaining non-decreasing order throughout.
Write a function that accepts this collection and returns the combined sorted result.
Rules
- Every integer from every input list must appear in the output exactly as many times as it appears across all inputs combined.
- Input lists may be empty. The collection itself may also be empty. When there are no integers at all, return an empty list.
- The order of elements in the output must be non-decreasing.
Constraints
0 ≤ k ≤ 10⁴wherekis the number of lists0 ≤ length of each list, and the sum of all list lengths is at most10⁵-10⁹ ≤ each integer ≤ 10⁹- Every input list is sorted in non-decreasing order
Examples
Example 1
Input: combine_sorted_lists([[1, 4, 9], [2, 2, 7], [3]])
Output: [1, 2, 2, 3, 4, 7, 9]
Example 2
Input: combine_sorted_lists([[], [-5, 0], [], [-5, 10]])
Output: [-5, -5, 0, 10]
Example 3
Input: combine_sorted_lists([])
Output: []
Hints
Hint 1
Consider how you would merge just two sorted lists using two pointers—one for each list.
Hint 2
Instead of merging lists one by one into a growing result, try splitting the collection in half recursively.
Hint 3
The recursion tree will have logarithmic depth in the number of lists, and each level processes all elements exactly once.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem combines two fundamental techniques: two-pointer merging and divide-and-conquer recursion.
Two-pointer merge: When you have two sorted lists, maintain one index into each. Compare the elements at both indices, append the smaller one to your result, and advance that index. Continue until one list is exhausted, then append everything remaining from the other. This runs in linear time relative to the combined length.
Divide-and-conquer over the collection: Rather than merging lists sequentially (which causes early elements to be copied repeatedly as the running result grows), split the collection in half. Recursively merge each half into a single sorted list, then use the two-pointer technique to merge those two results together.
The recursion operates on an index range [start, end):
- If the range is empty (
start >= end), return an empty list. - If the range contains exactly one list (
end - start == 1), return a copy of that list since it's already sorted. - Otherwise, find the midpoint, recursively solve both halves, and merge the two results.
Why It Works
The correctness follows by induction on the range size:
- Base cases: An empty range has no elements, so returning
[]is correct. A single list is already sorted and contains exactly the right elements. - Inductive step: Assume both recursive calls return correctly sorted lists with exactly the elements from their respective halves. The two-pointer merge then preserves every element exactly once (nothing is dropped or duplicated) and maintains sorted order by always selecting the minimum remaining element from both inputs.
Using <= in the comparison makes the merge stable, which is good practice even when merging plain integers.
Complexity
Let N be the total number of elements and k be the number of lists.
Time: O(N log k + k)
- The recursion tree has depth approximately log₂ k.
- At each depth level, every element participates in exactly one two-pointer merge, contributing O(N) work per level.
- The
+ kaccounts for visiting every list, including empty ones.
Space: O(N + log k)
- Each merge creates a new output list, but lists at any moment hold disjoint portions of the input.
- Recursion depth is O(log k), which is at most about 14 for k = 10⁴.
For comparison, merging lists sequentially (first with second, that result with third, etc.) costs O(N·k) in the worst case, which is far too slow when k = 10⁴.
Edge Cases
- Empty collection: returns
[]immediately - Lists that are empty: contribute nothing to the result
- Single list: returned as a copy
- Duplicates within or across lists: all preserved
- Negative numbers and extreme values (±10⁹): handled correctly since only comparisons are used
Solution
def combine_sorted_lists(lists: list[list[int]]) -> list[int]:
def merge_two(left, right):
i = j = 0
result = []
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
def merge_range(start, end):
if start >= end:
return []
if end - start == 1:
return list(lists[start])
middle = (start + end) // 2
return merge_two(merge_range(start, middle), merge_range(middle, end))
return merge_range(0, len(lists))