Minimum Interval to Include Each Query
HardNeetCode 150 IntervalsProblem
Each element of intervals is a range [start, end], and its size is
end - start + 1. Each element of queries is a number on the line.
For every query, find the size of the smallest interval that contains it, meaning
start ≤ query ≤ end. If no interval contains it, the answer for that query is
-1. Return the answers in the same order as queries.
Constraints
- 1 ≤ intervals.length ≤ 10⁵
- 1 ≤ queries.length ≤ 10⁵
- intervals[i].length == 2
- 1 ≤ start ≤ end ≤ 10⁷
- 1 ≤ queries[j] ≤ 10⁷
Examples: pick one to animate
Solutions
Time: Sorting the intervals and the queries costs O(n log n + m log m); every interval is pushed and popped at most once, each in O(log n).
Space: The heap can hold all n intervals, and the sorted query order and the answer list take O(m).
Answer the queries from smallest to largest. Keep the intervals sorted by start. For each query, push every interval that has started (start at most the query) onto a min-heap ordered by size. Then pop intervals from the top while they end before the query: since queries only grow, those can never help again. If the heap is not empty, its top is the smallest interval that still contains the query; otherwise the answer is -1.