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 - 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]
Constraints:
nums.length == k1 <= k <= 35001 <= nums[i].length <= 50-105 <= nums[i][j] <= 105nums[i] is sorted in non-decreasing order.In this approach, we use a min-heap to keep track of the smallest element across all lists, and a variable to track the current maximum from the lists. Initially, insert the first element of each list into the heap along with the list index and element index. The range [min, max] is updated as we extract the smallest element from the heap and add the next element from the respective list. The process continues until any one list is exhausted, ensuring the range includes elements from all lists.
This Python solution uses a min-heap to store the current minimum element along with its list and index. The heapifies the first element of each list and iteratively extracts minimum elements, updating the range when a new smaller range is found. For advanced elements, new entries get pushed into the min-heap. This continues until one list runs out.
C++
Time Complexity: O(n * log k), as each operation on the heap takes O(log k), performed for all elements.
Space Complexity: O(k), where k is the number of lists, due to storage in the heap.
In this approach, we maintain an array to store current indices for each list. Similarly, while keeping track of the maximum and minimum values, traverse the lists to update current positions and check the potential range. The update continues as long as all lists contribute a number to the current range.
This Java solution uses a priority queue to track indices of the elements. The priority queue allows the smallest element across current elements to be easily managed. For any move of the index, it maintains a new input keeping the maximal substantiality in check.
JavaScript
Time Complexity: O(n * log k) since using a heap.
Space Complexity: O(k) for minimum entries.
| Approach | Complexity |
|---|---|
| Using Min-Heap and Two Pointers | Time Complexity: O(n * log k), as each operation on the heap takes O(log k), performed for all elements. |
| Tracking Indices of Current Elements | Time Complexity: O(n * log k) since using a heap. |
Smallest Range Covering Elements from K Lists - Leetcode 632 - Python • NeetCodeIO • 14,731 views views
Watch 9 more video solutions →Practice Smallest Range Covering Elements from K Lists with our built-in code editor and test cases.
Practice on FleetCode