Smallest Range Covering Elements From K Lists Problem
Description
LeetCode Problem 632.
You have k lists of sorted integers in non-decreasingorder. Find the smallest range that includes at least one number from each of the k lists.
We define the range [a, b] is smaller than range [c, d] if b - a < d - c or a < c if b - a == d - c.
Example 1:
Input: nums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]
Output: [20,24]
Explanation:
List 1: [4, 10, 15, 24,26], 24 is in range [20,24].
List 2: [0, 9, 12, 20], 20 is in range [20,24].
List 3: [5, 18, 22, 30], 22 is in range [20,24].
Example 2:
Input: nums = [[1,2,3],[1,2,3],[1,2,3]]
Output: [1,1]
Example 3:
Input: nums = [[10,10],[11,11]]
Output: [10,11]
Example 4:
Input: nums = [[10],[11]]
Output: [10,11]
Example 5:
Input: nums = [[1],[2],[3],[4],[5],[6],[7]]
Output: [1,7]
Constraints:
- nums.length == k
- 1 <= k <= 3500
- 1 <= nums[i].length <= 50
- -10^5 <= nums[i][j] <= 10^5
- nums[i]is sorted in non-decreasing order.
Solution
Approach: Min-Heap Holding One Element per List
Pick one element from every list. The smallest range containing all of them is [smallest picked, largest picked]. The question is which picks to try.
Start with the first element of every list. To make the range smaller, raising the largest pick cannot help, so the only useful move is to raise the smallest pick: replace it with the next element of its own list. Repeating this moves through the candidates in increasing order of their lower end, and every range that can be optimal is checked along the way.
To find the smallest pick quickly, keep the current elements in a min-heap of (value, list index, position), and keep currentMax, the largest current element:
- Push the first element of each list and set
currentMaxto the largest of them. - Pop the smallest entry
low. The range[low, currentMax]covers every list; keep it if it is narrower than the best so far. - If that list has no next element, stop: every later range would be missing this list.
- Otherwise push its next element and update
currentMaxif the new element is larger. Go back to step 2.
Ties need no extra code: the lower ends we pop never decrease, so the first range found with the smallest width also has the smallest a. Keep a new range only when it is strictly narrower.
For Example 1, the start is {4, 0, 5}, giving [0, 5]. Popping 0 brings in 9 ([4, 9]), popping 4 brings in 10 ([5, 10]), and so on, until [20, 24] with {24, 20, 22}, the narrowest one.
Complexity: O(N log k) time, where N is the total number of elements and k is the number of lists: each element is pushed and popped at most once. O(k) space for the heap.
import heapq
class Solution:
def smallestRange(self, nums: List[List[int]]) -> List[int]:
# One current element per list: (value, list index, position in that list).
heap = [(row[0], i, 0) for i, row in enumerate(nums)]
heapq.heapify(heap)
current_max = max(row[0] for row in nums)
best_low, best_high = heap[0][0], current_max
while True:
low, i, j = heapq.heappop(heap) # the smallest current element
# [low, current_max] holds one element of every list.
if current_max - low < best_high - best_low:
best_low, best_high = low, current_max
if j + 1 == len(nums[i]):
break # list i is used up: no later range can include it
next_value = nums[i][j + 1]
heapq.heappush(heap, (next_value, i, j + 1))
current_max = max(current_max, next_value)
return [best_low, best_high]