Problem Description
Given k sorted lists, find the smallest range [a, b] such that at least one number from each list falls in the range. The range is considered smaller if (b - a) is smaller, or if equal, the lower a is prioritized.
Key Insights
- Use a min heap to maintain the smallest current element among the selected elements from each list.
- Track the current maximum among the chosen elements to easily compute the range.
- Iteratively replace the minimum element with the next element from the same list and update the current maximum.
- Stop when one of the lists is exhausted, as the range must include at least one element from each list.
Space and Time Complexity
Time Complexity: O(N log k), where N is the total number of elements across all lists. Space Complexity: O(k) for the heap, plus additional space for storing the range.
Solution
The solution uses a min heap (priority queue) that stores a tuple containing the current element, the index of the list it comes from, and its index in that list. Initially, the first element from each list is inserted into the heap and the current maximum among them is tracked. In each iteration, the smallest element is removed (heap root) which provides the current minimum, and the range [current_min, current_max] is assessed. If the list from which the minimum element was extracted has a next element, that element is inserted into the heap and the current maximum is updated if necessary. This process continues until one of the lists is exhausted.