Smallest Range Covering Elements from K Lists
Difficulty: Hard · Pattern: Heap & Priority Queue · LeetCode #632
You have k lists of integers, each sorted in ascending order. Find the smallest range [a, b] that contains at least one number from each list. Range [a,b] is smaller than [c,d] if b−a < d−c, or if they're equally wide and a < c.
Example
text
nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]] → [20,24]
(24 from list 1, 20 from list 2, 22 from list 3)
nums = [[1,2,3],[1,2,3],[1,2,3]] → [1,1]Hints
- Pick one element from each list. The range covering them is
[min, max]. - To shrink that range, the only useful move is to advance the list that holds the minimum. Advancing any other list can only raise the max.
- A min-heap gives you the current minimum. Track the max separately.
Approach
This is a k-way merge with a window:
text
heap = [(list[i][0], i, 0) for each list]; hi = max of those
best = (-inf, inf)
loop:
(lo, i, j) = heap.min
if hi - lo < best width: best = (lo, hi)
if j + 1 == len(list i): stop # can't advance; any further range would miss list i
pop; push (list[i][j+1], i, j+1); hi = max(hi, list[i][j+1])Each element enters the heap once: O(N log k), where N is the total number of elements. Ties on width resolve automatically, because the minimum only increases over time and we update only on a strictly smaller width.
Complexity
Time: O(N log k). Space: O(k).
Python solution
import heapq
def smallestRange(nums):
heap = [(lst[0], i, 0) for i, lst in enumerate(nums)]
heapq.heapify(heap)
hi = max(lst[0] for lst in nums)
best = [heap[0][0], hi]
while True:
lo, i, j = heap[0]
if hi - lo < best[1] - best[0]:
best = [lo, hi]
if j + 1 == len(nums[i]):
return best
nxt = nums[i][j + 1]
heapq.heapreplace(heap, (nxt, i, j + 1))
hi = max(hi, nxt)JavaScript solution
function smallestRange(nums) {
const heap = [];
const less = (a, b) => a[0] < b[0] || (a[0] === b[0] && a[1] < b[1]);
const up = (i) => { while (i > 0) { const p = (i - 1) >> 1; if (!less(heap[i], heap[p])) break; [heap[i], heap[p]] = [heap[p], heap[i]]; i = p; } };
const down = (i) => { for (;;) { const l = 2 * i + 1, r = l + 1; let m = i; if (l < heap.length && less(heap[l], heap[m])) m = l; if (r < heap.length && less(heap[r], heap[m])) m = r; if (m === i) return; [heap[i], heap[m]] = [heap[m], heap[i]]; i = m; } };
let hi = -Infinity;
nums.forEach((lst, i) => { heap.push([lst[0], i, 0]); up(heap.length - 1); hi = Math.max(hi, lst[0]); });
let best = [heap[0][0], hi];
for (;;) {
const [lo, i, j] = heap[0];
if (hi - lo < best[1] - best[0]) best = [lo, hi];
if (j + 1 === nums[i].length) return best;
const nxt = nums[i][j + 1];
heap[0] = [nxt, i, j + 1]; down(0);
hi = Math.max(hi, nxt);
}
}