Combine Several Pre-Sorted Lists Into One Sorted List
Heaps, Sorting & SearchAuto-graded · 24 test casesLast updated
Tests merging K nondecreasing integer lists into a single sorted list, preserving duplicates and handling empty lists, using a heap or pairwise merging.
You are given a list called lists. Each element of lists is itself a list of integers, already arranged in nondecreasing (ascending, ties allowed) order.
Write a function that produces one new list containing every integer from every inner list, arranged in nondecreasing order.
Rules
- Every occurrence of a value must appear in the output. If a value shows up three times across the inputs, it appears three times in the result.
- Inner lists may be empty, and they may have different lengths.
listsitself may be empty, in which case the result is an empty list.- Values may be negative, zero, or positive.
- Return a freshly built list. Do not modify the input lists.
The result is simply the sorted multiset union of all the inputs, so there is only one correct output for any given input. Aim to exploit the fact that each inner list is already sorted, rather than throwing everything into one list and sorting it from scratch.
Constraints
0 <= len(lists)- Each inner list is sorted in nondecreasing order and may be empty.
- Elements are integers (negatives and duplicates allowed).
- The total number of elements across all inner lists fits comfortably in memory.
Examples
Example 1
Input: combine_sorted_lists([[1, 3, 5], [2, 4, 6]])
Output: [1, 2, 3, 4, 5, 6]
Example 2
Input: combine_sorted_lists([[-5, -1, 2], [0, 2, 9, 10]])
Output: [-5, -1, 0, 2, 2, 9, 10]
Example 3
Input: combine_sorted_lists([[], [-3, -3], [], [1, 4, 4]])
Output: [-3, -3, 1, 4, 4]
Example 4
Input: combine_sorted_lists([[1, 2, 2, 7], [1, 1, 3], [-2, 8]])
Output: [-2, 1, 1, 1, 2, 2, 3, 7, 8]
Hints
Hint 1
At any moment, the smallest value not yet output must be the first unused element of one of the inner lists.
Hint 2
Keep a min-heap holding one candidate per non-empty inner list. Store the value together with the list index and the position so you know where to continue from.
Hint 3
After popping the smallest candidate, push the next element from the same inner list if there is one. Skip empty inner lists when building the initial heap.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Because every inner list is sorted, the smallest element not yet placed in the output is always the first unused element of one of the lists. So at any time we only need to compare at most K candidates, one per list.
A min-heap makes finding the smallest candidate cheap:
- For each non-empty inner list, push a tuple
(first_value, list_index, 0)onto the heap. - Pop the smallest tuple and append its value to the result.
- If that list has another element after the one just used, push the next element as
(value, list_index, next_position). - Repeat until the heap is empty.
Empty inner lists are never pushed, so they are ignored. An empty lists leaves the heap empty from the start, giving [].
Why it is correct
The heap always contains exactly one entry for each inner list that still has unused elements: its current front. The overall minimum of all unused elements must be the front of some list (since each list is sorted), so it is in the heap, and popping the heap minimum yields it. Pushing the successor of the popped element restores the invariant. Each element is output exactly once, so duplicates are preserved, and the output is produced in nondecreasing order.
The extra indices in the tuple make comparisons between equal values deterministic and tell us where to continue in each list.
Complexity
Let N be the total number of elements and K the number of inner lists.
- Time: O(N log K), since each element is pushed and popped once at O(log K) cost.
- Extra space: O(K) for the heap, plus O(N) for the output.
An alternative with the same time bound is to merge lists pairwise in rounds using a two-pointer merge. Merging them one after another into a growing accumulator is slower, up to O(N * K). Concatenating and sorting costs O(N log N).
Reference solution
import heapq
from typing import List
def combine_sorted_lists(lists: List[List[int]]) -> List[int]:
heap = []
result = []
for list_index, items in enumerate(lists):
if items:
heapq.heappush(heap, (items[0], list_index, 0))
while heap:
value, list_index, position = heapq.heappop(heap)
result.append(value)
next_position = position + 1
if next_position < len(lists[list_index]):
heapq.heappush(
heap,
(lists[list_index][next_position], list_index, next_position),
)
return result