Example 1
- Input
- intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5]
- Output
- [3,3,1,4]
Query 2 is covered best by [2,4] (size 3); query 3 also by [2,4]; query 4 by [4,4] (size 1); query 5 only by [3,6] (size 4).
You are given a list of intervals and a list of query points, and each query asks for the shortest interval covering it. Return those minimum sizes in the original query order, or -1 wherever nothing covers the query.
You are given a 2D integer array intervals and an integer array queries. For each query point q, find the interval with start <= q <= end that has the smallest size, where size is end - start + 1.
Return an array holding that minimum size per query in the original query order, or -1 for any query no interval contains.
Query 2 is covered best by [2,4] (size 3); query 3 also by [2,4]; query 4 by [4,4] (size 1); query 5 only by [3,6] (size 4).
Query 2 fits [2,3] (size 2); query 19 fits nothing (-1); query 5 fits [2,5] (size 4); query 22 fits [20,25] (size 6).
Only point 4 is covered, with inclusive size 1. Both copies of query 4 receive their own answer, and answers stay in the original unsorted query order.
At query 1 the singleton wins. At query 4 both shorter intervals have expired, so [1,10] wins with size 10. The endpoint 10 is still included.
The maximum allowed endpoint does not change inclusive arithmetic: the interval contains ten million integer points, and both boundaries are covered.
Each query asks for the smallest containing interval, not the nearest endpoint. In Example 1, query 4 belongs to four intervals but the singleton [4,4] wins with size 1. Sorting queries lets us reuse candidate intervals: once their start is reached they become eligible, and once their end is passed they can never help a later query. A minimum heap chooses by interval size, while stored ends let us discard candidates that have expired.
Reveal Brute Force: intuition, complexity, and code
When queries can be reordered internally, sort them to make candidate eligibility monotone, then use a heap keyed by the requested optimum and lazy expiry at the root. Store original indices to restore the external answer order.