Merge K Sorted Lists to Find Smallest Elements
Heaps, Sorting & SearchAuto-graded · 23 test casesLast updated
Tests efficient multi-way merge using a min-heap to extract the k smallest values from multiple sorted arrays without flattening the entire input.
You receive m sorted integer arrays and a target count k. Each array is already ordered from smallest to largest.
Your task is to extract the k smallest integers from across all the arrays combined, returning them in sorted order. When a value appears more than once—whether in the same array or different arrays—count each occurrence separately. If fewer than k total elements exist, return everything you have, still sorted.
The challenge is efficiency: your approach should scale with the number of arrays and the size of k, not with the total element count. Avoid concatenating everything into one giant array and sorting it.
Constraints
0 ≤ m ≤ 10⁴(number of arrays)0 ≤ len(arrays[i]) ≤ 10⁵for each array0 ≤ k ≤ 10⁵-10⁹ ≤ arrays[i][j] ≤ 10⁹- Every input array is sorted in non-decreasing order
Examples
Example 1
Input: merge_k_smallest([[1, 4, 7], [2, 5, 8], [3, 6, 9]], 5)
Output: [1, 2, 3, 4, 5]
Example 2
Input: merge_k_smallest([[], [2, 2], [1, 3]], 4)
Output: [1, 2, 2, 3]
Example 3
Input: merge_k_smallest([[5, 10], [3]], 10)
Output: [3, 5, 10]
Hints
Hint 1
Think about which elements are candidates for the next smallest value at any given moment—you only need to consider the current front of each array.
Hint 2
A min-heap can track the smallest available element across all arrays. Each time you extract one, advance that array's pointer and push its next element.
Hint 3
Python's heapq.merge can perform a lazy k-way merge; pair it with itertools.islice to stop after exactly k elements without processing the rest.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem calls for a multi-way merge with early termination. Because each array is already sorted, the smallest unconsumed element must be sitting at the front of one of the arrays. We never need to look deeper into an array until we've taken its current front.
A min-heap maintains one candidate per array: the element currently at that array's read position. On each iteration, pop the global minimum from the heap, add it to the result, and push the next element from that same array (if any remain). Stop once you've collected k elements or exhausted all arrays.
Python's heapq.merge implements exactly this pattern as a generator. It lazily yields elements in sorted order from multiple iterables without materializing the full merge. Wrapping it with itertools.islice(..., k) pulls at most k values, ensuring no extra work is done beyond what's needed.
Why It Works
The heap enforces a simple invariant: before each extraction, it holds the smallest available element from every non-empty array. Since each array is sorted, any element deeper in that array is at least as large as its front. Therefore, the heap's minimum is the global minimum across all unconsumed values.
After popping an element, replacing it with the next element from the same array restores the invariant. By induction, the sequence of pops produces elements in non-decreasing order, and the i-th pop yields the i-th smallest element overall.
Duplicates are handled naturally—each occurrence occupies a distinct position in some array, so each is yielded independently.
If total elements number fewer than k, the generator simply runs out and islice returns everything available.
Empty arrays contribute nothing; they're skipped automatically.
Complexity
Let m be the number of arrays and N the total element count.
-
Time: O(m + k log m)
Initial heap construction frommfronts takes O(m). Each of thekextractions involves a heap pop and push, costing O(log m) each. Elements beyond the firstkare never touched. Compare this with naive concatenate-and-sort, which would be O(N log N)—infeasible when N approaches 10⁹. -
Space: O(m + k)
O(m) for the heap and iterator state, O(k) for the output list.
Implementation
import heapq
from itertools import islice
from typing import List
def merge_k_smallest(arrays: List[List[int]], k: int) -> List[int]:
if k <= 0:
return []
return list(islice(heapq.merge(*arrays), k))