Minimum Interval to Include Each Query

HardIntervals · Offline Queries · Heap🧩 Intervals & Line SweepLeetCode #1851 ↗Updated

Problem

You get closed intervals intervals[i] = [left, right], whose size is right - left + 1, and an array queries. For each query q, report the size of the smallest interval with left ≤ q ≤ right, or -1 if none contains it. Answers must be returned in the original query order.
Inputintervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5]Output[3,3,1,4]
Inputintervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22]Output[2,-1,4,6]

1 ≤ intervals.length, queries.length ≤ 105  ·  1 ≤ left ≤ right ≤ 107  ·  1 ≤ queries[j] ≤ 107

Try it yourself

Java
class Solution {
    public int[] minInterval(int[][] intervals, int[] queries) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Answer queries offline in increasing order. As the query value grows, intervals only ever become eligible (left ≤ q) or expire (right < q), never come back — so one min-heap keyed by size can follow the whole sweep.
PatternIntervals & Line Sweep

Instinct See [start, end] pairs, meetings, bookings or the word "overlap"? Sort by an endpoint, then sweep left to right carrying one running fact.

Memory hack Sort, then sweep - start time to merge, end time to choose, +1/-1 events to count the crowd.

Open the Intervals & Line Sweep guide →

Approaches

Brute ForceScan All Intervals per Query

Time O(n·q)Space O(1) extra

For each query, look at every interval, keep those that contain the query and remember the smallest size. Straightforward, but with 105 of each it is 1010 checks.

Java
public int[] minInterval(int[][] intervals, int[] queries) {
    int[] ans = new int[queries.length];
    for (int j = 0; j < queries.length; j++) {
        int q = queries[j], best = Integer.MAX_VALUE;
        for (int[] iv : intervals) {
            if (iv[0] <= q && q <= iv[1]) best = Math.min(best, iv[1] - iv[0] + 1);
        }
        ans[j] = best == Integer.MAX_VALUE ? -1 : best;
    }
    return ans;
}

Perfect as a correctness reference; far too slow at full scale.

At a glance

LevelApproachTimeSpace
Brute ForceScan All Intervals per QueryO(n·q)O(1) extra
OptimalSorted Queries + Min-Heap by SizeO(n log n + q log q)O(n + q)
Common pitfalls
  • Answering in sorted order and forgetting to write results back to original indices.
  • Computing size as right - left — the interval is closed, add 1.
  • Removing expired intervals eagerly from the middle of the heap — lazy popping suffices.
Interview tips
  • Say “offline” early: sorting queries is allowed because all are known upfront.
  • Justify why an interval that expired for one query never helps a later one.
  • Mention the alternative: sort intervals by size and fill queries with a union-find.
Pattern
Offline sweep + heap → many range-membership queries where items enter and leave as the query value grows.
My notes saved in this browser