632. Smallest Range Covering Elements from K Lists
Problem
Given k sorted lists, return the smallest range [a, b] that contains at least one number from every list. A range is smaller if it is narrower, or equally wide and starts lower.
Example: [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]] → [20,24]
Constraints: k ≤ 3500; lists up to 50 long.
K-way merge with a min-heap holding one element from each list, plus the current maximum of those elements. The heap top and the max form a range containing one element of every list. Advance the list that holds the minimum (the only move that can shrink the range); stop when that list runs out.
Complexity: O(N log k) for N total elements.
class Solution:
def smallestRange(self, nums: List[List[int]]) -> List[int]:
heap = [(row[0], i, 0) for i, row in enumerate(nums)]
heapify(heap)
hi = max(row[0] for row in nums)
best = [heap[0][0], hi]
while True:
lo, i, j = heappop(heap)
if hi - lo < best[1] - best[0]:
best = [lo, hi]
if j + 1 == len(nums[i]):
return best
nxt = nums[i][j + 1]
hi = max(hi, nxt)
heappush(heap, (nxt, i, j + 1))
assert Solution().smallestRange([[4, 10, 15, 24, 26], [0, 9, 12, 20], [5, 18, 22, 30]]) == [20, 24]
assert Solution().smallestRange([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) == [1, 1]
assert Solution().smallestRange([[1], [2], [3]]) == [1, 3]
assert Solution().smallestRange([[10, 10], [11, 11]]) == [10, 11]
class Solution {
public int[] smallestRange(List<List<Integer>> nums) {
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0])); // {value, list, index}
int hi = Integer.MIN_VALUE;
for (int i = 0; i < nums.size(); i++) {
pq.add(new int[]{nums.get(i).get(0), i, 0});
hi = Math.max(hi, nums.get(i).get(0));
}
int[] best = {pq.peek()[0], hi};
while (true) {
int[] top = pq.poll();
if (hi - top[0] < best[1] - best[0]) best = new int[]{top[0], hi};
List<Integer> row = nums.get(top[1]);
if (top[2] + 1 == row.size()) return best;
int nxt = row.get(top[2] + 1);
hi = Math.max(hi, nxt);
pq.add(new int[]{nxt, top[1], top[2] + 1});
}
}
}
type entry struct{ v, i, j int } // value, list, position
type entryHeap []entry
func (h entryHeap) Len() int { return len(h) }
func (h entryHeap) Less(i, j int) bool { return h[i].v < h[j].v }
func (h entryHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *entryHeap) Push(x any) { *h = append(*h, x.(entry)) }
func (h *entryHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
func smallestRange(nums [][]int) []int {
h, hi := &entryHeap{}, math.MinInt
for i, row := range nums { // one pointer per list; the range is [heap min, hi]
heap.Push(h, entry{row[0], i, 0})
hi = max(hi, row[0])
}
best := []int{(*h)[0].v, hi}
for {
e := heap.Pop(h).(entry)
if hi-e.v < best[1]-best[0] {
best = []int{e.v, hi}
}
if e.j+1 == len(nums[e.i]) { // a list is exhausted
return best
}
next := nums[e.i][e.j+1]
hi = max(hi, next)
heap.Push(h, entry{next, e.i, e.j + 1})
}
}