In a distributed data system, you have K pre-sorted partition files that must be merged
into a single sorted stream. However, you have a strict memory budget and cannot load all data
into memory at once.
Given K sorted partitions (each represented as a list of integers):
partitions: List[List[int]] # K lists, each internally sorted
Implement:
def merge_sorted_partitions(
partitions: List[List[int]],
max_heap_size: int
) -> List[int]:
"""
Merge K sorted partitions into a single sorted list using at most max_heap_size
elements in memory at any given time.
Text
Args:
partitions: list of K pre-sorted lists
max_heap_size: maximum number of elements to hold in the heap
Returns:
A fully merged and sorted list of all integers from all partitions
"""
Constraints:
- Each partition is already sorted internally (smallest to largest)
- K can be up to 1,000
- Total elements across all partitions can be up to 10 million
- Heap size must not exceed max_heap_size at any point
- Optimize for O((n*K) log K) time complexity
Input Format:
Line 1: K max_heap_size
Lines 2 to K+1: space-separated integers for each partition
Output Format:
One integer per line, in sorted order