Narrowest Window Touching Every Sorted Array
Heaps, Sorting & SearchAuto-graded · 20 test casesLast updated
Find the tightest inclusive interval that holds at least one value from each of several sorted arrays, using a k-way merge with a min-heap and a tracked maximum.
You are given a collection of k integer arrays, each sorted in non-decreasing order. Find an inclusive interval [lo, hi] such that every array has at least one element x with lo <= x <= hi.
Many intervals may qualify, so use this ordering to pick one. Interval [p, q] is better than [r, s] when:
q - p < s - r(it is strictly narrower), orq - p == s - randp < r(equal width, but it starts further left).
Return the best qualifying interval as [lo, hi].
Arrays may contain repeated values and negative numbers. The same value can appear in several arrays.
Input
lists: a list ofklists of integers. Each inner list is sorted in non-decreasing order.
Output
- A list of two integers
[lo, hi], the best interval under the ordering above.
Constraints
k == len(lists)1 <= k <= 35001 <= len(lists[i]) <= 50- The total number of elements across all lists is at most
10^5 -10^5 <= lists[i][j] <= 10^5- Each
lists[i]is sorted in non-decreasing order
Examples
Example 1
Input: narrowest_cover([[4, 10, 15, 24, 26], [0, 9, 12, 20], [5, 18, 22, 30]])
Output: [20, 24]
Example 2
Input: narrowest_cover([[1, 2, 3], [1, 2, 3], [1, 2, 3]])
Output: [1, 1]
Hints
Hint 1
Imagine choosing one element from each array. The smallest interval covering those choices is determined by their minimum and maximum.
Hint 2
Start with the first element of every array. To shrink the interval, the only move that can help is replacing the current minimum with the next element from the same array.
Hint 3
Use a min-heap to get the current minimum quickly, and keep the current maximum in a separate variable. Stop as soon as the array that supplied the minimum has no further elements.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Any qualifying interval is at least as wide as the interval spanned by some choice of one element per array. So we can think of the problem as picking one element from each array and minimizing max - min of the picks.
- Start with the first element of each array and put them all in a min-heap, storing
(value, list index, position). Track the maximum of these picks in a variable, since a heap only gives cheap access to its minimum. - The interval
[heap minimum, tracked maximum]covers every array. Compare it to the best interval found so far, using the width and then left-endpoint ordering. - To look for something better, the only useful move is to raise the minimum. Pop the minimum and replace it with the next element from the same array. Moving any other pick forward could only keep or raise the maximum, so it cannot help. The maximum can't be lowered, because pointers only move forward.
- Update the tracked maximum if the new element exceeds it. It never needs to decrease, because the new element is at least as large as the one it replaced, and we only ever remove the minimum.
- If the popped element was the last of its array, stop. Every later state would have to leave that array without a pick.
Why it is correct
Let [a, b] be the best interval under the ordering. Each array has an element in [a, b].
Pointers only advance when their element is the current minimum. Consider the first moment the heap minimum is >= a. Before it, any popped element was < a, so no pointer has moved past the first element >= a in its array. No array can have been exhausted either, since each has an element >= a. At this moment every pointer therefore sits exactly on the first element >= a in its array. That element is <= b, because each array has some element in [a, b].
So the heap minimum is >= a and the tracked maximum is <= b. The interval [min, max] lies inside [a, b] and covers every array. Since [a, b] is optimal, the two must be equal. The algorithm evaluates this state, and the comparison rule matches the problem's ordering, so no worse interval can replace it afterward.
The heap minimum only increases during the run. Later intervals with equal width therefore never have a smaller left endpoint, and the tie-break behaves correctly.
Complexity
- Time:
O(N log k), whereNis the total number of elements. Each element is pushed and popped at most once, and each heap operation costsO(log k). - Space:
O(k), since the heap always holds one entry per list.
Reference solution
import heapq
from typing import List
def narrowest_cover(lists: List[List[int]]) -> List[int]:
heap = []
cur_max = float('-inf')
# Seed with the first element of every list.
for idx, arr in enumerate(lists):
heapq.heappush(heap, (arr[0], idx, 0))
if arr[0] > cur_max:
cur_max = arr[0]
best_lo = heap[0][0]
best_hi = cur_max
while heap:
cur_min, idx, pos = heapq.heappop(heap)
width = cur_max - cur_min
best_width = best_hi - best_lo
if width < best_width or (width == best_width and cur_min < best_lo):
best_lo, best_hi = cur_min, cur_max
pos += 1
if pos == len(lists[idx]):
break # this list can no longer contribute a larger value
nxt = lists[idx][pos]
heapq.heappush(heap, (nxt, idx, pos))
if nxt > cur_max:
cur_max = nxt
return [best_lo, best_hi]