Merge Sorted Streams with Memory Constraint
Heaps, Sorting & SearchAuto-graded · 22 test casesLast updated
Tests heap-based merging of multiple sorted sequences under strict O(k) space while maintaining stable duplicate handling.
You are given k sorted lists of integers and a limit count. Your task is to merge these lists into a single sorted sequence and return the first count elements from that sequence.
Each input list is already sorted in ascending order. When multiple lists contain the same value, you must preserve all duplicates and maintain stability: if list i and list j both contain value v, and i < j, then all copies of v from list i must appear before any copy of v from list j in the output.
Your solution must use O(k) auxiliary space, where k is the number of input lists. You may assume all integers fit in memory, but you cannot load entire lists at once beyond what is needed for the merging process.
Write a function that takes a list of sorted integer lists and a count, then returns a list containing up to count elements in globally sorted order with stable duplicates.
Constraints
- 0 ≤ k ≤ 10⁴ (number of input lists)
- 0 ≤ count ≤ 10⁶
- 0 ≤ length of each list ≤ 10⁶
- -10⁹ ≤ integer values ≤ 10⁹
- Each input list is sorted in non-decreasing order
- Auxiliary space must be O(k), not counting the output array
Examples
Example 1
Input: merge_sorted_lists([[1, 4, 7], [2, 3, 8], [0, 5, 9]], 6)
Output: [0, 1, 2, 3, 4, 5]
Example 2
Input: merge_sorted_lists([[1, 1, 3], [1, 2, 2], []], 8)
Output: [1, 1, 1, 2, 2, 3]
Example 3
Input: merge_sorted_lists([[5, 6, 7]], 2)
Output: [5, 6]
Example 4
Input: merge_sorted_lists([[], [], []], 10)
Output: []
Hints
Hint 1
The smallest unprocessed element overall must be at the front of one of the remaining lists.
Hint 2
Use a min-heap to track the current front element of each active list, along with which list it came from.
Hint 3
When values are equal, the list index can serve as a tie-breaker to ensure stable output.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that since each input list is already sorted, the globally smallest remaining element must be the current head of one of the lists. We don't need to examine elements further into any list until we've processed its earlier elements.
We maintain a min-heap containing exactly one entry per active list: the current front element paired with its source list index. The heap ensures we can extract the global minimum in O(log k) time. The list index serves a dual purpose: it tells us which list to advance after popping, and it acts as a stable tie-breaker when values are equal (Python's tuple comparison is lexicographic, so smaller indices win ties).
The algorithm proceeds as follows:
- Initialize the heap with the first element from each non-empty list, paired with its list index
- Maintain an array tracking the current position in each list
- Repeatedly extract the minimum from the heap, append it to the output, advance the corresponding list, and push its next element (if any) back into the heap
- Stop when we've collected
countelements or the heap becomes empty (all lists exhausted)
This is correct because the heap invariant guarantees we always extract the true global minimum among all unprocessed elements. Stability follows from tuple comparison: when list 0 and list 3 both have value 5 at their heads, the heap will store (5, 0) and (5, 3), and (5, 0) compares smaller, so list 0's 5 is extracted first.
Complexity
- Time: O((k + count) log k). We perform k heap insertions to initialize (or O(k) if using
heapify), then up tocountextract-advance-insert cycles, each costing O(log k). - Space: O(k) auxiliary space for the heap and position tracking array. The output array requires O(count) space but is typically counted separately as the return value.
Solution
import heapq
from typing import List
def merge_sorted_lists(lists: List[List[int]], count: int) -> List[int]:
if count <= 0 or not lists:
return []
heap = []
indices = [0] * len(lists)
for list_idx, lst in enumerate(lists):
if lst:
heapq.heappush(heap, (lst[0], list_idx))
output = []
while heap and len(output) < count:
val, list_idx = heapq.heappop(heap)
output.append(val)
indices[list_idx] += 1
current_pos = indices[list_idx]
current_list = lists[list_idx]
if current_pos < len(current_list):
heapq.heappush(heap, (current_list[current_pos], list_idx))
return output