Minimum Interval to Include Each Query
Minimum Interval to Include Each Query is LeetCode 1851 (Hard). Each interval [left, right] covers every integer from left to right, and its size is right - left + 1. For each value in queries, return the size of the smallest interval that contains it, or -1 if none does.
- Answers must come back in the original order of
queries. - Both lists can hold 10⁵ items, so checking every interval for every query (10¹⁰ pairs) is too slow.
- 1 <= intervals.length <= 10⁵
- 1 <= queries.length <= 10⁵
- intervals[i].length == 2
- 1 <= leftᵢ <= rightᵢ <= 10⁷
- 1 <= queries[j] <= 10⁷
Intuition
Answer the queries from smallest to largest, not in the order given. Then the intervals that can contain the current query change in a simple way:
- Starting: an interval becomes a candidate once its
leftis at or below the query, and that stays true for every larger query. So intervals sorted byleftare added once and never re-checked. - Ending: a candidate whose
rightis below the query is dead, and it stays dead for every larger query.
Keep the candidates in a min-heap ordered by size. The smallest one on top is the answer, as long as it has not ended. A dead interval only matters when it reaches the top, so it is thrown away at that moment and never earlier.
Many range-style queries over a fixed set of intervals, with answers allowed in any order you like, point to offline processing: sort the queries, sweep once, and keep the active items in a heap or ordered set.
Approach
Before reading on, sort the queries and picture sweeping from left to right. Decide when an interval should join the pool of candidates, when it should leave, and what structure gives the smallest candidate quickly. Aim for O((n + m) log n).
Sort the intervals and the query positions
Sort intervals by left. Sort the indices 0..m-1 by their query value instead of sorting queries itself, so each answer can be written back to its original slot.
Add every interval that has started
For the next query x, push each interval with left <= x onto a min-heap as (size, right), moving one pointer through the sorted intervals. The pointer never resets, because an interval that started before x also started before every later query.
Throw away dead intervals from the top
While the top of the heap has right < x, pop it: it ends before x, so it cannot hold this query or any larger one. Dead intervals deeper in the heap can wait, since they only get in the way once they are the smallest.
Read the answer
If the heap is not empty, its top started at or before x and ends at or after x, so it contains x, and no candidate is smaller. Write its size to ans[index]. An empty heap means no interval contains x, and the slot keeps -1.
Code in Python, C++ and Java
Common pitfalls
Sorting the queries and losing their order
queries.sort()
for j, x in enumerate(queries):
...
ans[j] = heap[0][0]for idx in sorted(range(len(queries)), key=lambda k: queries[k]):
x = queries[idx]The answers come out in sorted order. For intervals = [[1, 2], [1, 10]] and queries = [5, 2] the expected output is [10, 2], but this returns [2, 10].
Popping intervals that end exactly at the query
while heap and heap[0][1] <= x:
while heap and heap[0][1] < x:
Both ends are inclusive, so an interval with right == x still contains x. With intervals = [[1, 3]] and queries = [3] the wrong test pops the only interval and returns -1 instead of 3.
Storing only the size in the heap
heapq.heappush(heap, right - left + 1)
heapq.heappush(heap, (right - left + 1, right))
Without right there is no way to tell whether the top interval has ended. For intervals = [[1, 1], [1, 9]] and queries = [5] the size-1 interval stays on top and the answer comes out 1 instead of 9.
Edge cases
Every candidate has ended, so the popping loop empties the heap and the slot keeps -1. Later queries can still get answers from intervals that start after the gap.
The second copy finds nothing new to push or pop and reads the same top, so both slots get the same size.
Complexity
Minimum Interval to Include Each Query FAQ
Why is it fine to leave dead intervals inside the heap?
A dead interval below the top never changes an answer: the answer is read only from the top, and the popping loop removes a dead interval the moment it gets there. Removing them early would need a search through the heap for no gain.
Is there a way to solve it without a heap?
Yes. Sort the intervals by size, smallest first, and keep the unanswered query values in a sorted set. Each interval takes every value still in the set between its left and right, records its size for them and removes them, so a query is answered by the smallest interval that covers it. It also runs in O(n log n + (n + m) log m), but needs an ordered set, which Python has only through a library.
Can two intervals with the same size cause a wrong answer?
No. Ties only decide which of two equal sizes sits on top, and both report the same size. If the one on top has ended it is popped, and the other is checked next.