KatInterview

Merge K Sorted Lists to Find Smallest Elements

Heaps, Sorting & SearchAuto-graded · 23 test cases

Last 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 array
  • 0 ≤ 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.