You have k lists of sorted integers in non-decreasing order. 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 - cora < 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].
We need one element from each of \(k\) sorted lists so the covering range is shortest. Index combinations do not scale.
Flatten \((value, group)\) pairs and sort. The task is the shortest window that covers all \(k\) groups; expand the right end and shrink the left while a counter still sees \(k\) groups.
We construct a data item \((x, i)\) for each number \(x\) and its group \(i\), and store these items in a new array \(t\). Then, we sort \(t\) by the value of the numbers (similar to merging multiple sorted arrays into a new sorted array).
Next, we traverse each data item in \(t\), focusing on the group to which each number belongs. We use a hash table to record the groups of numbers within the sliding window. If the number of groups is \(k\), it means the current window meets the problem's requirements. At this point, we calculate the start and end positions of the window and update the answer.
The time complexity is \(O(n \times \log n)\), and the space complexity is \(O(n)\). Here, \(n\) is the total number of numbers in all arrays.
Method 1 materializes every value. Because each list is sorted, a min-heap of the \(k\) current pointers plus a running maximum already describes a candidate range; advance the list that produced the minimum. Space is \(O(k)\).