LeetCode #1851 Hard

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.
Constraints
  • 1 <= intervals.length <= 10⁵
  • 1 <= queries.length <= 10⁵
  • intervals[i].length == 2
  • 1 <= leftᵢ <= rightᵢ <= 10⁷
  • 1 <= queries[j] <= 10⁷
intervalsheapsortingoffline-query
Open on LeetCode ↗
02

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 left is at or below the query, and that stays true for every larger query. So intervals sorted by left are added once and never re-checked.
  • Ending: a candidate whose right is 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.

How to spot this pattern

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.

03

Approach

Try it first

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).

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]:
▶3 intervals.sort()
▶4 ans = [-1] * len(queries)
▶5 heap = []
▶6 i = 0
▶7 for idx in sorted(range(len(queries)), key=lambda k: queries[k]):
▶8 x = queries[idx]
▶9 while i < len(intervals) and intervals[i][0] <= x:
▶10 left, right = intervals[i]
▶11 heapq.heappush(heap, (right - left + 1, right))
▶12 i += 1
▶13 while heap and heap[0][1] < x:
▶14 heapq.heappop(heap)
▶15 if heap:
▶16 ans[idx] = heap[0][0]
▶17 return ans
1 to 4size 42 to 4size 33 to 6size 44 to 4size 1123456heapemptyqueryanswer2345queries in order 2, 3, 4, 5, intervals by start
heapempty
The intervals are sorted by where they start, and the queries will be handled from smallest to largest. Each answer still goes back to the query's own slot, so the bottom row keeps the input order.
query 21 to 4size 42 to 4size 33 to 6size 44 to 4size 1123456heap4ends 4queryanswer23451 to 4 has started → add it, size 4
query2
pushsize 4, ends 4
This interval starts at 1, at or before the query 2, so it is a candidate. It will also have started for every larger query, which is why the pointer never goes back.
query 21 to 4size 42 to 4size 33 to 6size 44 to 4size 1123456heap3ends 44ends 4queryanswer23452 to 4 has started → add it, size 3
query2
pushsize 3, ends 4
This interval starts at 2, at or before the query 2, so it is a candidate. It will also have started for every larger query, which is why the pointer never goes back.
query 21 to 4size 42 to 4size 33 to 6size 44 to 4size 1123456heap3ends 44ends 4queryanswer23345query 2 → smallest live interval, size 3
query2
answer3
The top interval started at or before 2 and ends at 4, at or after it, so it contains 2. Nothing in the heap is smaller, so query 2 gets 3.
query 31 to 4size 42 to 4size 33 to 6size 44 to 4size 1123456heap3ends 44ends 44ends 6queryanswer233453 to 6 has started → add it, size 4
query3
pushsize 4, ends 6
This interval starts at 3, at or before the query 3, so it is a candidate. It will also have started for every larger query, which is why the pointer never goes back.
query 31 to 4size 42 to 4size 33 to 6size 44 to 4size 1123456heap3ends 44ends 44ends 6queryanswer233345query 3 → smallest live interval, size 3
query3
answer3
The top interval started at or before 3 and ends at 4, at or after it, so it contains 3. Nothing in the heap is smaller, so query 3 gets 3.
query 41 to 4size 42 to 4size 33 to 6size 44 to 4size 1123456heap1ends 43ends 44ends 44ends 6queryanswer2333454 to 4 has started → add it, size 1
query4
pushsize 1, ends 4
This interval starts at 4, at or before the query 4, so it is a candidate. It will also have started for every larger query, which is why the pointer never goes back.
query 41 to 4size 42 to 4size 33 to 6size 44 to 4size 1123456heap1ends 43ends 44ends 44ends 6queryanswer2333415query 4 → smallest live interval, size 1
query4
answer1
The top interval started at or before 4 and ends at 4, at or after it, so it contains 4. Nothing in the heap is smaller, so query 4 gets 1.
query 51 to 4size 42 to 4size 33 to 6size 44 to 4size 1123456heap1ends 43ends 44ends 44ends 6queryanswer2333415smallest ends at 4, before 5 → drop it
query5
top ends4
The smallest candidate, size 1, stopped at 4. It cannot contain 5 or any later, larger query, so it leaves the heap for good. Dead intervals further down are left alone until they reach the top.
query 51 to 4size 42 to 4size 33 to 6size 44 to 4dropped123456heap3ends 44ends 44ends 6queryanswer2333415smallest ends at 4, before 5 → drop it
query5
top ends4
The smallest candidate, size 3, stopped at 4. It cannot contain 5 or any later, larger query, so it leaves the heap for good. Dead intervals further down are left alone until they reach the top.
query 51 to 4size 42 to 4dropped3 to 6size 44 to 4dropped123456heap4ends 44ends 6queryanswer2333415smallest ends at 4, before 5 → drop it
query5
top ends4
The smallest candidate, size 4, stopped at 4. It cannot contain 5 or any later, larger query, so it leaves the heap for good. Dead intervals further down are left alone until they reach the top.
query 51 to 4dropped2 to 4dropped3 to 6size 44 to 4dropped123456heap4ends 6queryanswer23334154query 5 → smallest live interval, size 4
query5
answer4
The top interval started at or before 5 and ends at 6, at or after it, so it contains 5. Nothing in the heap is smaller, so query 5 gets 4.
1 to 4dropped2 to 4dropped3 to 6size 44 to 4dropped123456heap4ends 6queryanswer23334154answer: 3, 3, 1, 4
return[3, 3, 1, 4]
Each answer was written to its query's original slot, so the list already matches the input order: 3, 3, 1, 4. Each interval was added once and dropped at most once.
05

Common pitfalls

Sorting the queries and losing their order

✗ Wrong
queries.sort()
for j, x in enumerate(queries):
    ...
    ans[j] = heap[0][0]
✓ Right
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

✗ Wrong
while heap and heap[0][1] <= x:
✓ Right
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

✗ Wrong
heapq.heappush(heap, right - left + 1)
✓ Right
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.

06

Edge cases

A query in a gap between intervals

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.

Repeated query values

The second copy finds nothing new to push or pop and reads the same top, so both slots get the same size.

07

Complexity

Time
O(n log n + m log m)
Space
O(n + m)
Sorting costs O(n log n) for the intervals and O(m log m) for the query order. Each interval is pushed once and popped at most once, O(log n) each. The heap, the order list and the answers take O(n + m) space.
08

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.