Smallest Range Covering Elements from K Lists (LeetCode 632): Solution and Explanation

Hard
Array
Hash Table
Greedy
Sliding Window
Sorting
Heap

You have k lists, each sorted in ascending order. Find the narrowest range [a, b] that contains at least one number from every list, preferring the range with the smaller start when two ranges have the same width.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Any valid range is defined by picking one number from each list: the range runs from the smallest pick to the largest pick. A brute force would try every combination of picks, which is the product of the list lengths and hopeless. A better framing is to merge all the numbers and run a sliding window that must contain every list, but there is an even more direct view that uses the fact that each list is already sorted.

Imagine one pointer per list, all starting at the first element. The current picks give a candidate range from the minimum pick to the maximum pick. To find a narrower range, moving any pointer other than the minimum's can only raise the maximum or leave it, which never helps. The only move that might shrink the range is advancing the list that holds the minimum, because that raises the low end.

So the algorithm is a k-way merge. A min heap gives us the current minimum in O(log k), and we track the current maximum in a plain variable, since the maximum only ever grows as pointers advance. Each time we pop the minimum we compare the range [min, max] with the best so far, then push the next element from the same list. When any list runs out we stop, because without that list no later window can cover every list.

Approach: Min heap k-way merge

  1. Push the first element of every list into a min heap as (value, list_index, element_index) and set max_val to the largest of those first elements.
  2. Initialize result to [heap[0][0], max_val], the range covering the first element of each list.
  3. Pop the smallest entry (min_val, list_idx, elem_idx) from the heap.
  4. If max_val - min_val is smaller than the width of result, update result to [min_val, max_val].
  5. If the popped element was the last in its list, stop, because no range without that list is valid.
  6. Otherwise push the next element of that list and update max_val if the new value is larger, then repeat.

Step-by-step example

nums = [[1,5,8], [4,12], [7,8,10]]
  1. The heap starts with 1, 4 and 7. max_val is 7 and result is [1,7] with width 6.
  2. Pop 1. Width 7 - 1 = 6 is not smaller. Push 5 from list 0; max_val stays 7.
  3. Pop 4. Width 7 - 4 = 3 is smaller, so result becomes [4,7]. Push 12 from list 1; max_val becomes 12.
  4. Pop 5. Width 12 - 5 = 7 is not smaller. Push 8 from list 0.
  5. Pop 7. Width 12 - 7 = 5 is not smaller. Push 8 from list 2.
  6. Pop 8 from list 0. Width 4 is not smaller than 3, and list 0 is exhausted, so the loop ends. The answer is [4,7].

Code: Python, Java, C++

1class Solution:
2    def smallestRange(self, nums: List[List[int]]) -> List[int]:
3        # Min heap: (value, list_index, element_index)
4        heap = [(row[0], i, 0) for i, row in enumerate(nums)]
5        heapq.heapify(heap)
6
7        max_val = max(row[0] for row in nums)
8        result = [heap[0][0], max_val]
9
10        while True:
11            min_val, list_idx, elem_idx = heapq.heappop(heap)
12
13            if max_val - min_val < result[1] - result[0]:
14                result = [min_val, max_val]
15
16            if elem_idx + 1 == len(nums[list_idx]):
17                break
18
19            next_val = nums[list_idx][elem_idx + 1]
20            max_val = max(max_val, next_val)
21            heapq.heappush(heap, (next_val, list_idx, elem_idx + 1))
22
23        return result

Time and space complexity

Time

O(N log k)

N is the total number of elements. Each element is pushed and popped at most once, and every heap operation costs O(log k) because the heap never holds more than k entries.

Space

O(k)

The heap holds exactly one entry per list at any time.

Other approaches

Merge and sliding window (time O(N log N), space O(N))

Flatten every number into (value, list_index) pairs, sort them, then slide a window that tracks how many distinct lists it covers with a count map. Shrink from the left while all k lists are present. It is a classic minimum window pattern and easy to adapt, at the cost of a full sort and O(N) extra memory.

Common mistakes

  • Recomputing the maximum by scanning the heap each time, which turns O(log k) steps into O(k). The maximum only increases, so a single variable is enough.
  • Continuing after one list is exhausted. Once a list has no more elements, every later window would miss it.
  • Using <= when comparing widths, which replaces an earlier range with a later one of the same width and breaks the smaller start tie rule.
  • Pushing only values without the list and element indices, which leaves no way to fetch the next element from the right list.

Frequently asked questions

Why do we always advance the list with the minimum?

The range is [min, max] of the current picks. Advancing any other list cannot raise the minimum, so it can only keep the width the same or make it larger. Advancing the minimum's list is the only move that can narrow the range.

Is this problem the same as minimum window substring?

The sliding window alternative is the same pattern: after merging and sorting, find the shortest window that contains at least one item of each of k kinds. The heap version is a specialized form that uses the sorted lists to avoid the full sort.

Why does the heap only need k entries?

We keep exactly one current pointer per list, so the heap holds one candidate per list. Popping one entry and pushing its successor keeps the size at k until a list runs out.