Smallest Range Covering Elements from K Lists (LeetCode 632): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Push the first element of every list into a min heap as
(value, list_index, element_index)and setmax_valto the largest of those first elements. - Initialize
resultto[heap[0][0], max_val], the range covering the first element of each list. - Pop the smallest entry
(min_val, list_idx, elem_idx)from the heap. - If
max_val - min_valis smaller than the width ofresult, updateresultto[min_val, max_val]. - If the popped element was the last in its list, stop, because no range without that list is valid.
- Otherwise push the next element of that list and update
max_valif the new value is larger, then repeat.
Step-by-step example
nums = [[1,5,8], [4,12], [7,8,10]]
- The heap starts with 1, 4 and 7.
max_valis 7 andresultis [1,7] with width 6. - Pop 1. Width 7 - 1 = 6 is not smaller. Push 5 from list 0;
max_valstays 7. - Pop 4. Width 7 - 4 = 3 is smaller, so
resultbecomes [4,7]. Push 12 from list 1;max_valbecomes 12. - Pop 5. Width 12 - 5 = 7 is not smaller. Push 8 from list 0.
- Pop 7. Width 12 - 7 = 5 is not smaller. Push 8 from list 2.
- 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 result1class Solution {
2 public int[] smallestRange(List<List<Integer>> nums) {
3 PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> a[0] - b[0]);
4 int maxVal = Integer.MIN_VALUE;
5
6 for (int i = 0; i < nums.size(); i++) {
7 heap.offer(new int[]{nums.get(i).get(0), i, 0});
8 maxVal = Math.max(maxVal, nums.get(i).get(0));
9 }
10
11 int[] result = {heap.peek()[0], maxVal};
12
13 while (true) {
14 int[] curr = heap.poll();
15 int minVal = curr[0], listIdx = curr[1], elemIdx = curr[2];
16
17 if (maxVal - minVal < result[1] - result[0]) {
18 result = new int[]{minVal, maxVal};
19 }
20
21 if (elemIdx + 1 == nums.get(listIdx).size()) break;
22
23 int nextVal = nums.get(listIdx).get(elemIdx + 1);
24 maxVal = Math.max(maxVal, nextVal);
25 heap.offer(new int[]{nextVal, listIdx, elemIdx + 1});
26 }
27
28 return result;
29 }
30}1class Solution {
2public:
3 vector<int> smallestRange(vector<vector<int>>& nums) {
4 auto cmp = [](auto& a, auto& b) { return a[0] > b[0]; };
5 priority_queue<vector<int>, vector<vector<int>>, decltype(cmp)> heap(cmp);
6 int maxVal = INT_MIN;
7
8 for (int i = 0; i < nums.size(); i++) {
9 heap.push({nums[i][0], i, 0});
10 maxVal = max(maxVal, nums[i][0]);
11 }
12
13 vector<int> result = {heap.top()[0], maxVal};
14
15 while (true) {
16 auto curr = heap.top();
17 heap.pop();
18 int minVal = curr[0], listIdx = curr[1], elemIdx = curr[2];
19
20 if (maxVal - minVal < result[1] - result[0]) {
21 result = {minVal, maxVal};
22 }
23
24 if (elemIdx + 1 == nums[listIdx].size()) break;
25
26 int nextVal = nums[listIdx][elemIdx + 1];
27 maxVal = max(maxVal, nextVal);
28 heap.push({nextVal, listIdx, elemIdx + 1});
29 }
30
31 return result;
32 }
33};Time and space complexity
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.
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.