AlgoInsight

DSA problem

Smallest Range Covering Elements from K Lists

HardK-Way MergePattern: K-Way Mergetop300AmazonGoogleMicrosoftBloombergApple

You have k lists of sorted integers in non-decreasing order. Find the smallest range that includes at least one number from each of the k lists. We define the range [a, b] to be smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c.

A brute-force search across all combinations of one element per list explodes combinatorially, so we need a smarter sweep. The crucial observation is that at any moment during a left-to-right sweep across all lists combined, if we keep a "frontier" of exactly one element per list, then the smallest and largest values among those frontier elements define a range that, by construction, includes at least one number from every list.

To find the optimal range we want to minimize max - min over all such frontiers. We can maintain the frontier with a min-heap of size k: pop the smallest value, record the range [min, max] if it improves on the best seen so far, then advance that list's pointer and push the new value. We must track the current maximum across the frontier separately because the heap only gives us efficient access to the minimum.

The sweep terminates as soon as one list is exhausted: at that point we cannot keep a representative from every list, so no further valid range can be formed. The total work is O(N log k) where N is the total number of elements across all lists — each element is pushed and popped exactly once — and the auxiliary space is O(k) for the heap.

This problem is a clean application of the K-Way Merge pattern: it walks through the merged sorted view of all lists while extracting an answer that depends on the simultaneous frontier, not on any single merged element.

Examples

Example 1
Input: nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]
Output: [20,24]
Explanation: The range [20,24] contains 24 from the first list, 20 from the second, and 22 from the third. Its length 4 is the smallest possible.
Example 2
Input: nums = [[1,2,3],[1,2,3],[1,2,3]]
Output: [1,1]
Explanation: Every list contains 1, so the range [1,1] of length 0 covers all three lists and is optimal.
Example 3
Input: nums = [[10,10],[11,11]]
Output: [10,11]
Explanation: Pick 10 from the first list and 11 from the second; the range [10,11] of length 1 is the smallest that covers both.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

arrayheapk-way-mergepriority-queuesliding-window

Browse all DSA problems