import heapq
from typing import List, Iterator, Any, Union
def k_way_merge(sorted_lists: List[List[int]]) -> List[int]:
"""
Merges k sorted lists into a single sorted list using a min-heap.
Args:
sorted_lists: List of k sorted lists (each representing a sorted file's contents).
Returns:
A single sorted list containing all elements from the input lists.
Time Complexity: O(N log K), where N is total elements, K is number of lists.
Space Complexity: O(K) for the heap.
"""
if not sorted_lists:
return []
heap: List[tuple[int, int, int]] = [] # (value, list_idx, elem_idx)
# Initialize heap with first element from each non-empty list
for i, lst in enumerate(sorted_lists):
if lst:
heapq.heappush(heap, (lst[0], i, 0))
result = []
while heap:
val, list_idx, elem_idx = heapq.heappop(heap)
result.append(val)
# Push next element from the same list if available
if elem_idx + 1 < len(sorted_lists[list_idx]):
next_val = sorted_lists[list_idx][elem_idx + 1]
heapq.heappush(heap, (next_val, list_idx, elem_idx + 1))
return result
# Example usage
if __name__ == "__main__":
lists = [
[1, 4, 7],
[2, 5, 8],
[3, 6, 9],
[10]
]
merged = k_way_merge(lists)
print(merged) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
For Actual Files (Streaming Version)
If merging sorted text files (one integer per line), use this iterator-based version for memory efficiency:
python
import heapq
from typing import Iterator, List
from contextlib import contextmanager
import os
@contextmanager
def open_files(file_paths: List[str], mode: str = 'r') -> Iterator[List]:
"""Context manager to safely open and close multiple files."""
handles = []
try:
handles = [open(path, mode) for path in file_paths]
yield handles
finally:
for h in handles:
h.close()
def k_way_merge_files(file_paths: List[str], output_path: str = None) -> Iterator[int]:
"""
Generator for merging k sorted files (one int per line) into a stream.
Optionally writes to an output file.
Args:
file_paths: List of paths to sorted input files.
output_path: Optional output file path; if None, yields values.
Yields:
Merged sorted integers (one per line if writing to file).
"""
if not file_paths:
return
with open_files(file_paths) as file_handles_list:
heap: List[tuple[int, int, Iterator[str]]] = [] # (value, file_idx, iterator)
# Create line iterators and initialize heap
for i, fh in enumerate(file_handles_list):
it = iter(fh.readline, '') # Iterator over lines until EOF
try:
first_line = next(it).strip()
if first_line:
val = int(first_line)
heapq.heappush(heap, (val, i, it))
except StopIteration:
pass # Empty file
out_file = open(output_path, 'w') if output_path else None
try:
while heap:
val, file_idx, it = heapq.heappop(heap)
if output_path:
out_file.write(f"{val}\n")
else:
yield val
# Push next from same file
try:
next_line = next(it).strip()
if next_line:
next_val = int(next_line)
heapq.heappush(heap, (next_val, file_idx, it))
except StopIteration:
pass # File ended
finally:
if out_file:
out_file.close()
# Example usage (files must exist: file1.txt, file2.txt, etc.)
# list(k_way_merge_files(['file1.txt', 'file2.txt'])) # Streams merged values
# k_way_merge_files(['file1.txt', 'file2.txt'], 'merged.txt') # Writes to file
This implementation is efficient, handles duplicates/empty files/unequal lengths, and is adaptable to custom iterables (e.g., replace int(line) with any parser).