SDE & MLE Prep

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))