Problem overview
The method minInterval receives a list intervals and a list queries. Each interval is a pair [left, right] that holds every whole number from left to right, both ends included, so its size is right - left + 1. For each query, find the smallest interval that holds it. The method returns a list with those sizes, in the order of queries, and uses -1 for a query that no interval holds.
With intervals = [[2, 6], [4, 5], [1, 9], [8, 8]] and queries = [5, 8, 1, 3] the answer is [2, 1, 9, 5]. The number 5 lies in [2, 6], [4, 5] and [1, 9], and the smallest of those is [4, 5], size 2. The number 1 lies only in [1, 9], size 9. With intervals = [[10, 12], [30, 31]] and queries = [11, 20, 31, 9] the answer is [3, -1, 2, -1], because no interval holds 20 or 9.
The lesson asks for O(n log n + q log q) time, for n intervals and q queries. Both lists can hold 100,000 entries, in any order, and intervals may overlap or repeat.
Approach: answer queries from small to large
Checking every interval for every query takes O(n · q), which is 10 billion steps at the limits. The speed-up comes from the order of the work.
Answer the queries from smallest to largest, and sort the intervals by their left end. When the query is q, the intervals that start at or before q are the only candidates, and since queries only grow, an interval that starts before one query also starts before all later ones. So each interval can be added once, when the first query reaches its start.
The candidates are kept in a min-heap of pairs (size, right). Pairs compare by their first value, so the smallest interval is always on top. Before reading the top, drop the intervals that end before q. They can't hold q, and since later queries are larger, they can't hold any later query either. Only the top needs checking: an expired interval deeper in the heap is removed when it reaches the top.
Everything left in the heap starts at or before q and ends at or after it, so the top is the smallest interval holding q. If the heap is empty, the answer stays -1.
Because queries are answered out of order, we also remember each query's original position and write the result there.
Step by step
- Sort
intervalsby left end:intervals.sort(key=lambda interval: interval[0]). - Sort the query positions by value:
order = sorted(range(len(queries)), key=lambda k: queries[k]). This sorts the indexes, not the values, so we keep track of where each answer belongs. - Create
answer = [-1] * len(queries), one -1 per query. A query that finds an interval overwrites it. - Create
heap = []. With theheapqmodule, a plain list works as a min-heap, with the smallest pair atheap[0]. - Create
i = 0, the index of the next interval to add. - Loop with
koverorder. - Set
q = queries[k], the query's value. - Add the intervals that start at or before
q: whilei < len(intervals)andintervals[i][0] <= q, unpackstart, end = intervals[i], push(end - start + 1, end)withheapq.heappush, and add 1 toi. The size goes first so the smallest interval floats to the top, and the end tells us later when the interval stops being useful. - Drop the expired intervals: while
heapis not empty andheap[0][1] < q, callheapq.heappop(heap). - Answer the query: if
heapis not empty, setanswer[k] = heap[0][0]. - Return
answer.
On the first example, the sorted intervals are [1, 9], [2, 6], [4, 5] and [8, 8], and the sorted query positions are [2, 3, 0, 1], which are the queries 1, 3, 5 and 8. For each query, the table shows the heap after the two inner loops (pairs of size and end) and the answer:
query 1: heap [(9, 9)] answer 9
query 3: heap [(5, 6), (9, 9)] answer 5
query 5: heap [(2, 5), (5, 6), (9, 9)] answer 2
query 8: heap [(1, 8), (2, 5), (5, 6), (9, 9)] answer 1
The heap contents are listed in sorted order here, for readability. For query 8, the pairs (2, 5) and (5, 6) are still in the heap although they ended before 8. They are not on top, so the loop leaves them alone, and they can't affect the answer: the top (1, 8) is smaller than both. If they ever reach the top, the cleanup loop drops them then. Results are written to answer[k], so the final list is [2, 1, 9, 5], in the order of the original queries.
The solution in Python
class Solution:
def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]:
intervals.sort(key=lambda interval: interval[0])
order = sorted(range(len(queries)), key=lambda k: queries[k])
answer = [-1] * len(queries)
heap = []
i = 0
for k in order:
q = queries[k]
while i < len(intervals) and intervals[i][0] <= q:
start, end = intervals[i]
heapq.heappush(heap, (end - start + 1, end))
i += 1
while heap and heap[0][1] < q:
heapq.heappop(heap)
if heap:
answer[k] = heap[0][0]
return answer
Python details:
heapqis a min-heap on a plain list.heappushandheappoptakeO(log n), andheap[0]reads the smallest item inO(1).- Tuples compare element by element. Two intervals of equal size are ordered by their right end, which is harmless here.
sortedreturns a new list, whileintervals.sort(...)sorts in place and returnsNone. The in-place sort reorders the caller'sintervals, butqueriesstays as it was, which matters becausequeries[k]is read by position.while heap and ...relies on an empty list being false, andandstops beforeheap[0]is read on an empty heap.
Complexity
Time: O(n log n + q log q). Sorting the intervals costs O(n log n) and sorting the query positions O(q log q). Each interval is pushed once and popped at most once, each in O(log n), so the heap work is O(n log n). Each query adds only constant work outside those pushes and pops.
Space: O(n + q). The heap holds up to n pairs, and order and answer hold q entries each.
Edge cases and common mistakes
- A query no interval holds. For
[[10, 12], [30, 31]]the queries 20 and 9 stay at -1: 9 comes before every start, and for 20 the interval[10, 12]is dropped as expired. - Repeated queries and shared ends. For
[[1, 3], [3, 5], [3, 3]]and[3, 3, 4]the answer is[1, 1, 3]. Both ends count, so 3 is in all three intervals, and the smallest is[3, 3]. The checkheap[0][1] < qkeeps an interval whose end equalsq. - Writing answers in sorted order. The result must follow the original order of
queries, which is why the loop writesanswer[k]and not an appended value. - Storing only the size in the heap. Without the right end there is no way to tell when an interval has expired.
- Forgetting the +1 in the size. The interval
[8, 8]holds one number, so its size is 1, not 0.
Testing
Results from running the method:
| intervals | queries | Result |
|---|---|---|
[[2, 6], [4, 5], [1, 9], [8, 8]] | [5, 8, 1, 3] | [2, 1, 9, 5] |
[[10, 12], [30, 31]] | [11, 20, 31, 9] | [3, -1, 2, -1] |
[[1, 3], [3, 5], [3, 3]] | [3, 3, 4] | [1, 1, 3] |
