Combine Several Ascending Sequences into One Sorted Sequence
Heaps, Sorting & SearchAuto-graded · 23 test casesLast updated
Merge k individually sorted integer arrays into a single sorted array, testing heap-based k-way merging or pairwise divide-and-conquer and the associated complexity analysis.
You are given a collection of k integer arrays. Every array is already sorted in non-decreasing (ascending) order. Some arrays may be empty.
Produce one array that contains every element from every input array, arranged in non-decreasing order.
Task
Implement combine_sorted_arrays(arrays), which receives a list of sorted lists of integers and returns a single sorted list holding all of their elements.
Rules
- Every element of every input array must appear in the output exactly as many times as it appears in the inputs. Duplicates, including duplicates that occur across different arrays, are all kept.
- The output must be in non-decreasing order.
- If the outer list is empty, or every inner list is empty, return an empty list.
- If there is only one inner list, its contents are the answer.
- Values may be negative, and the inner lists may have very different lengths.
Let N be the total number of elements across all arrays. A solution that simply concatenates everything and sorts is correct but ignores the fact that the inputs are already sorted. Aim for roughly O(N log k) time.
Constraints
0 <= k <= 10^4- Each inner list has length between
0and500 0 <= N <= 10^4in total (typical test sizes)- Each value is an integer in the range
[-10^4, 10^4] - Each inner list is sorted in non-decreasing order
Examples
Example 1
Input: combine_sorted_arrays([[1, 4, 5], [1, 3, 4], [2, 6]])
Output: [1, 1, 2, 3, 4, 4, 5, 6]
Example 2
Input: combine_sorted_arrays([[], [], []])
Output: []
Example 3
Input: combine_sorted_arrays([[1], [0]])
Output: [0, 1]
Hints
Hint 1
At every step, the next value to output must be the smallest among the first not-yet-used element of each array. How can you find that minimum quickly when k is large?
Hint 2
A min-heap holding at most one entry per array (the value plus which array and which position it came from) lets you pop the smallest in O(log k) and then push the next element from the same array.
Hint 3
Alternative: merge the arrays in pairs, round after round, like the merge step of merge sort. That takes about log2(k) rounds, each costing O(N), for O(N log k) overall. Merging them one after another into a growing result is slower, around O(kN).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Let N be the total number of elements and k the number of arrays.
Naive options first:
- Concatenate and sort:
O(N log N)time. It works but throws away the sortedness of the inputs. - Merge one array at a time into a running result: early elements get rescanned on every merge, giving about
O(kN).
The better approach is a k-way merge with a min-heap:
- For each non-empty array, push a tuple
(first_value, array_index, 0)into a min-heap. - Repeatedly pop the smallest tuple and append its value to the output.
- If that array has a next element, push
(next_value, array_index, next_position). - Stop when the heap is empty.
The heap never holds more than k entries, and each of the N elements is pushed and popped once, each at O(log k) cost.
Including the array index in the tuple means ties on value are broken by an integer, so comparisons are always well defined. Equal values are all kept.
Why it is correct
The heap always contains the smallest not-yet-output element of each non-exhausted array. Because each array is sorted, every remaining element of an array is at least as large as that array's current front. So the smallest value in the heap is the smallest remaining value overall, and it is the correct next output. Popping it and pushing its successor from the same array restores the invariant. By induction the output is sorted and uses every element exactly once. Empty inputs simply never enter the heap, so an empty or all-empty input yields an empty list.
Complexity
- Time:
O(N log k)(building the initial heap isO(k)). - Space:
O(k)for the heap, plus theO(N)output.
An alternative with the same time bound is pairwise divide-and-conquer: merge arrays two at a time with the standard two-pointer merge for about log2 k rounds, each round costing O(N).
Reference solution
import heapq
from typing import List
def combine_sorted_arrays(arrays: List[List[int]]) -> List[int]:
heap = []
for i, arr in enumerate(arrays):
if arr:
# (value, array index, position in that array)
heap.append((arr[0], i, 0))
heapq.heapify(heap)
result = []
while heap:
value, i, pos = heapq.heappop(heap)
result.append(value)
nxt = pos + 1
if nxt < len(arrays[i]):
heapq.heappush(heap, (arrays[i][nxt], i, nxt))
return result