Minimum Interval to Include Each Query (LeetCode 1851): Solution and Explanation
You have a list of inclusive intervals and a list of query points. For each query, find the size of the smallest interval that contains it, where size is right - left + 1, or return -1 if no interval contains it.
Watch it run step by step
Try your own input and write the code →Intuition
The brute force checks every interval for every query, which is O(n × q). With up to 100,000 of each that is ten billion checks, so we need to share work between queries.
The trick is to stop answering queries in the order given. If you process queries from smallest to largest, the set of intervals that could contain the current query changes in a very orderly way. An interval becomes a candidate once its start is at or before the query, and since queries only increase, it never stops satisfying that condition. It drops out once its end falls before the query, and it never comes back. That is a sweep line.
Among the live candidates we want the smallest size, which is what a min-heap is for. Push (size, end) when an interval's start is passed. Before answering, pop from the top while the smallest interval's end is before the query. Intervals that have expired but sit deeper in the heap do no harm, because they get removed the moment they reach the top. Since the answers are computed out of order, each query carries its original index so the result lands in the right slot.
Approach: Offline sweep with a min-heap
- Sort the intervals by start, and sort the queries by value while keeping their original indices.
- Initialize
resultto -1 for every query, an empty heap and a pointeri = 0into the intervals. - For each query
qin sorted order, push(end - start + 1, end)for every interval whose start is at mostq, advancingi. - Pop heap entries while the top interval's end is less than
q, since it cannot contain this or any later query. - If the heap is not empty, the top entry's size is the answer for this query's original index.
- Return
result.
Step-by-step example
intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5]
- Queries are already sorted. For
q = 2, push[1,4]as(4, 4)and[2,4]as(3, 4). The top is size 3 and its end 4 covers 2, so the answer is 3. - For
q = 3, push[3,6]as(4, 6). The top is still(3, 4), so the answer is 3. - For
q = 4, push[4,4]as(1, 4). The top(1, 4)covers 4, so the answer is 1. - For
q = 5, nothing new starts. Pop(1, 4),(3, 4)and(4, 4)because they end before 5. The top is(4, 6), so the answer is 4. - The result is
[3, 3, 1, 4].
Code: Python, Java, C++
1class Solution:
2 def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]:
3 intervals.sort()
4 sorted_queries = sorted(enumerate(queries), key=lambda x: x[1])
5 result = [-1] * len(queries)
6 heap = [] # (size, end)
7 i = 0
8
9 for idx, q in sorted_queries:
10 # Add all intervals that start <= q
11 while i < len(intervals) and intervals[i][0] <= q:
12 start, end = intervals[i]
13 heapq.heappush(heap, (end - start + 1, end))
14 i += 1
15
16 # Remove intervals that end < q
17 while heap and heap[0][1] < q:
18 heapq.heappop(heap)
19
20 if heap:
21 result[idx] = heap[0][0]
22
23 return result1class Solution {
2 public int[] minInterval(int[][] intervals, int[] queries) {
3 Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
4 int[][] sortedQueries = new int[queries.length][2];
5 for (int i = 0; i < queries.length; i++) {
6 sortedQueries[i] = new int[]{i, queries[i]};
7 }
8 Arrays.sort(sortedQueries, (a, b) -> a[1] - b[1]);
9
10 int[] result = new int[queries.length];
11 Arrays.fill(result, -1);
12 PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> a[0] - b[0]);
13 int i = 0;
14
15 for (int[] sq : sortedQueries) {
16 int idx = sq[0], q = sq[1];
17
18 while (i < intervals.length && intervals[i][0] <= q) {
19 int start = intervals[i][0], end = intervals[i][1];
20 heap.offer(new int[]{end - start + 1, end});
21 i++;
22 }
23
24 while (!heap.isEmpty() && heap.peek()[1] < q) {
25 heap.poll();
26 }
27
28 if (!heap.isEmpty()) {
29 result[idx] = heap.peek()[0];
30 }
31 }
32
33 return result;
34 }
35}1class Solution {
2public:
3 vector<int> minInterval(vector<vector<int>>& intervals, vector<int>& queries) {
4 sort(intervals.begin(), intervals.end());
5 vector<pair<int, int>> sortedQueries;
6 for (int i = 0; i < queries.size(); i++) {
7 sortedQueries.push_back({queries[i], i});
8 }
9 sort(sortedQueries.begin(), sortedQueries.end());
10
11 vector<int> result(queries.size(), -1);
12 priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> heap;
13 int i = 0;
14
15 for (auto& [q, idx] : sortedQueries) {
16 while (i < intervals.size() && intervals[i][0] <= q) {
17 int start = intervals[i][0], end = intervals[i][1];
18 heap.push({end - start + 1, end});
19 i++;
20 }
21
22 while (!heap.empty() && heap.top().second < q) {
23 heap.pop();
24 }
25
26 if (!heap.empty()) {
27 result[idx] = heap.top().first;
28 }
29 }
30
31 return result;
32 }
33};Time and space complexity
O(n log n + q log q)
Sorting costs O(n log n) and O(q log q). Each interval is pushed and popped at most once, at O(log n) per operation, and each query does constant work beyond those pops.
O(n + q)
The heap can hold all n intervals, and the sorted query list and result take O(q).
Other approaches
Brute force scan (time O(n × q), space O(q))
For every query, loop over all intervals, keep those that contain it, and track the smallest size. Fine for small inputs only.
Sort by size with union-find or ordered set (time O(n log n + q log q), space O(n + q))
Sort intervals by size and assign each one to all still-unanswered sorted queries it covers, using an ordered set or a union-find skip pointer to jump over answered queries. Every query is assigned once.
Common mistakes
- Answering queries in input order. The sweep only works when queries are increasing, so sort them and keep their indices.
- Popping only intervals whose end is before the previous query instead of the current one. The check must use the current
q. - Keying the heap by end instead of size. The top must be the smallest interval, and end is only needed for the expiry check.
- Computing size as
right - left. Intervals are inclusive, so the size isright - left + 1, which makes[4,4]size 1.
Frequently asked questions
Why sort the queries in Minimum Interval to Include Each Query?
Sorted queries turn the problem into a sweep line: intervals become eligible once and expire once, so each one is pushed and popped a single time. Keeping the original index puts each answer back in place.
Why is lazy deletion from the heap safe?
An expired interval only matters if it is at the top, and the loop removes any expired interval before reading the top. Expired entries deeper in the heap never influence an answer.
What is the time complexity?
O(n log n + q log q). Sorting dominates, and each interval enters and leaves the heap once.
What does the heap store?
Pairs of (size, end). Size orders the heap so the smallest interval is on top, and end decides when that interval can no longer cover a query.