Minimum Interval to Include Each Query
Problem
You are given intervals [left, right], where an interval's size is right - left + 1, and a list of query points. For each query, return the size of the smallest interval that contains it, or -1 if no interval does.
Examples
Constraints
- • 1 <= intervals.length, queries.length <= 10^5
- • 1 <= left <= right <= 10^7
- • 1 <= queries[j] <= 10^7
Hints & approach
Hint 1
Answering queries in sorted order lets you reuse work between them.
Hint 2
Sort intervals by left; as the query value grows, add every interval that has started.
Hint 3
Keep candidates in a min-heap keyed by size, and lazily drop ones whose right end is below the query.
Approachtry the hints first
Sort intervals by left and process queries in increasing order, remembering their original positions. For each query q, push every interval with left <= q onto a min-heap as (size, right). Then pop from the heap while the top's right < q, since those intervals ended before q and can never help later queries. The heap top, if any, is the smallest interval covering q; otherwise the answer is -1. Write each answer back to its original index.
Time O(n log n + q log q) · Space O(n + q)