15% off all plans & roadmaps Use code
See plansMinimum Interval to Include Each Query
- LeetCode 1851
- Hard
- Heap (Priority Queue) Patterns
- Scheduling / Minimum Cost (Greedy with Priority Queue)
Updated
TL;DR: Each query needs the smallest interval that covers it. Sort the queries, sweep them from smallest to largest, and keep a min-heap of intervals that have started while popping the ones that have ended.
Problem
You get an array intervals. Each element [l, r] is an interval that contains every integer from l through r. The size of an interval is r - l + 1.
For each value in queries, find the smallest interval that contains it, meaning l <= query <= r. Return an array with one answer per query, in the same order as queries. If no interval contains a query, its answer is -1.
Duplicate queries keep their own positions in the output. Treat both arrays as ordered sequences, and answer each query on its own.
Example 1
Input: intervals = [[4,9],[1,3],[7,12]], queries = [2,5,10,13] Output: [3,6,6,-1] Explanation: Query 2 is covered by [1,3], whose size is 3. Queries 5 and 10 are each covered by an interval of size 6, and no interval contains 13.
Example 2
Input: intervals = [[2,2],[1,8],[5,6],[8,10]], queries = [2,6,8,11] Output: [1,2,3,-1] Explanation: The single-point interval [2,2] is the best choice for 2, and [5,6] is best for 6. Query 8 is covered by [8,10] with size 3, and 11 is uncovered.
Example 3
Input: intervals = [[10,20],[12,12],[15,18]], queries = [12,12,17] Output: [1,1,4] Explanation: Both occurrences of 12 use the one-point interval [12,12]. For 17, [15,18] is smaller than [10,20].
Constraints
1 <= intervals.length <= 10^51 <= queries.length <= 10^5- Each element of
intervalscontains exactly two integers[l, r]. 1 <= l <= r <= 10^7for every interval[l, r].1 <= query <= 10^7for every query.- Queries may repeat, and intervals may overlap.
Constraints that matter
- With n and m both up to 10^5, comparing every query with every interval takes up to 10^10 checks. That rules out the nested scan.
- Values go up to 10^7, so an array indexed by value would be large and mostly empty. The method has to work on sorted values instead.
- Intervals overlap and queries repeat. You need a structure that returns the smallest active interval quickly, which points to a heap.
- Answers must follow the original query order. Any sorted processing has to keep each query's original index.
Hints
Hint 1
The pattern is a heap (priority queue) used inside a sweep.
Hint 2
Check every interval for every query.
Solution
Intuition
The pattern is a heap (priority queue) used inside a sweep. The sweep walks through sorted points, and the heap holds the candidates that are active at the current point.
Picture a train platform where each query is a stop, visited in order. Each interval is a shop that opens at its left end and closes at its right end, and the min-heap is the shelf of open shops sorted by size.
Every query asks the same question: which intervals cover this value? Sorting the queries makes that question change in one direction. An interval starts covering queries when the sweep reaches its left endpoint, and it stops covering them after the sweep passes its right endpoint. So each interval enters the candidate set once and leaves it once.
The answer is the smallest candidate at each step. A min-heap keyed by size puts that value at the top. Expired intervals can sit in the heap for a while, but they only matter when they reach the top. Queries only increase, so an expired interval never becomes useful again.
Worked example
Input: intervals = [[5,5]], queries = [5,5,4,6] Output: [1,1,-1,-1] Explanation: The only interval is the single point 5, so its size is 1. Both queries equal to 5 are covered and get 1. Query 4 is below the interval and query 6 is above it, so both get -1. The answers keep the order of the input queries.
Approach 1: Brute force
Check every interval for every query. An interval [l, r] covers a query q when l <= q <= r, and its size is r - l + 1. Keep the smallest size among the covering intervals, and write -1 if none cover the query.
This repeats work across queries. Each interval is compared with every query, even when the query is far from it. With 10^5 intervals and 10^5 queries, that is up to 10^10 comparisons, which is too slow.
Steps
- Create a result array of length m.
- For each query, set
bestto -1. - For each interval, test whether
l <= query <= r. - If it covers the query, compare its size with
bestand keep the smaller one. Treat -1 as 'not found' before comparing. - Store
bestat the query's position and return the array.
Dry run
Query 5 at index 0 is covered by [5,5], so its size 1 becomes the best. Query 5 at index 1 gives 1 again. Query 4 finds no interval with l <= 4, so it gives -1.
Query 6 has l = 5 <= 6, but r = 5 < 6, so it gives -1. The output is [1,1,-1,-1].
Complexity
| Time | O(n * m) |
|---|---|
| Space | O(1) beyond the output array |
Let n be the number of intervals and m the number of queries. The outer loop runs m times, and each run checks all n intervals, so the work is n * m checks. The method keeps only a few variables besides the output, so the extra space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]:
result = []
for query in queries:
best = -1
for left, right in intervals:
if left <= query <= right:
size = right - left + 1
if best == -1 or size < best:
best = size
result.append(best)
return resultJavaTested in our runner
class Solution {
public int[] minInterval(int[][] intervals, int[] queries) {
int[] result = new int[queries.length];
for (int i = 0; i < queries.length; i++) {
int best = -1;
for (int[] interval : intervals) {
int l = interval[0];
int r = interval[1];
if (l <= queries[i] && queries[i] <= r) {
int size = r - l + 1;
if (best == -1 || size < best) {
best = size;
}
}
}
result[i] = best;
}
return result;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
vector<int> minInterval(vector<vector<int>>& intervals, vector<int>& queries) {
vector<int> result(queries.size(), -1);
for (size_t i = 0; i < queries.size(); ++i) {
for (const auto& interval : intervals) {
int l = interval[0];
int r = interval[1];
if (l <= queries[i] && queries[i] <= r) {
int size = r - l + 1;
if (result[i] == -1 || size < result[i]) {
result[i] = size;
}
}
}
}
return result;
}
};JavaScriptTested in our runner
/**
* @param {number[][]} intervals
* @param {number[]} queries
* @return {number[]}
*/
var minInterval = function(intervals, queries) {
const result = [];
for (const q of queries) {
let best = -1;
for (const [l, r] of intervals) {
if (l <= q && q <= r) {
const size = r - l + 1;
if (best === -1 || size < best) {
best = size;
}
}
}
result.push(best);
}
return result;
};GoTested in our runner
func minInterval(intervals [][]int, queries []int) []int {
result := make([]int, len(queries))
for i, q := range queries {
best := -1
for _, iv := range intervals {
l, r := iv[0], iv[1]
if l <= q && q <= r {
size := r - l + 1
if best == -1 || size < best {
best = size
}
}
}
result[i] = best
}
return result
}C#Tested in our runner
public class Solution {
public int[] minInterval(int[][] intervals, int[] queries) {
int[] result = new int[queries.Length];
for (int i = 0; i < queries.Length; i++) {
int best = -1;
foreach (int[] interval in intervals) {
int l = interval[0];
int r = interval[1];
if (l <= queries[i] && queries[i] <= r) {
int size = r - l + 1;
if (best == -1 || size < best) {
best = size;
}
}
}
result[i] = best;
}
return result;
}
}The Scheduling / Minimum Cost (Greedy with Priority Queue) infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Scheduling / Minimum Cost (Greedy with Priority Queue)
Part of Heap (Priority Queue) Patterns
Approach 2: Sort queries, then min-heap sweepOptimalScheduling / Minimum Cost (Greedy with Priority Queue)
What's slow: the brute force compares each query with all n intervals. Most of those comparisons repeat work that a sorted sweep can skip.
The insight that fixes it: visit the queries in increasing order. An interval becomes a candidate when the sweep reaches its left endpoint, and it stops being useful after the sweep passes its right endpoint. A min-heap keyed by size keeps the smallest candidate at the top.
Each interval is pushed once and popped at most once. The sweep only removes expired entries from the top, because only the top decides the answer.
Steps
- Sort a copy of
intervalsby the left endpoint. - Build
order, the query indices sorted by query value. - Create a result array filled with -1 and an empty min-heap of
(size, right)pairs. - Set a pointer
nextto 0. - For each index in
order, push every interval withl <= query, storing(r - l + 1, r)and advancing the pointer. - Pop from the heap while its top has
right < query. - If the heap is not empty, write its top size at the query's original index.
- Return the result array.
Dry run
The sorted intervals are [5,5]. The sorted query order is value 4 (index 2), value 5 (index 0), value 5 (index 1), and value 6 (index 3). The table traces each query in that order.
| Step | Query (original index) | Pointer and push | Heap after cleanup | Answer written |
|---|---|---|---|---|
| 1 | 4 (index 2) | No push, since 5 > 4 | empty | answer[2] = -1 |
| 2 | 5 (index 0) | Push (1, 5), pointer = 1 | (1, 5) | answer[0] = 1 |
| 3 | 5 (index 1) | No push | (1, 5) | answer[1] = 1 |
| 4 | 6 (index 3) | No push | pop (1, 5) because 5 < 6, heap empty | answer[3] = -1 |
The result is [1,1,-1,-1], which matches the expected output.
Complexity
| Time | O(n log n + m log m) |
|---|---|
| Space | O(n + m) |
Let n be the number of intervals and m the number of queries. Sorting the intervals costs O(n log n), and sorting the query order costs O(m log m). Each interval is pushed once and popped at most once, and the heap holds at most n entries, so heap work totals O(n log n). The other work per query is O(1).
The extra space is O(n) for the sorted copy and the heap, plus O(m) for the query order.
PythonTested in our runner
from typing import List, Optional
import heapq
class Solution:
def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]:
ordered_intervals = sorted(intervals, key=lambda interval: interval[0])
query_order = sorted(range(len(queries)), key=lambda index: queries[index])
result = [-1] * len(queries)
candidates = []
interval_index = 0
for query_index in query_order:
query = queries[query_index]
# Add every interval that has started by this query.
while interval_index < len(ordered_intervals) and ordered_intervals[interval_index][0] <= query:
left, right = ordered_intervals[interval_index]
heapq.heappush(candidates, (right - left + 1, right))
interval_index += 1
# Remove intervals that ended before this query.
while candidates and candidates[0][1] < query:
heapq.heappop(candidates)
if candidates:
result[query_index] = candidates[0][0]
return resultJavaTested in our runner
import java.util.*;
class Solution {
public int[] minInterval(int[][] intervals, int[] queries) {
Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
Integer[] queryOrder = new Integer[queries.length];
for (int i = 0; i < queries.length; i++) {
queryOrder[i] = i;
}
Arrays.sort(queryOrder, (a, b) -> Integer.compare(queries[a], queries[b]));
int[] result = new int[queries.length];
Arrays.fill(result, -1);
PriorityQueue<int[]> candidates = new PriorityQueue<>((a, b) -> a[0] != b[0] ? Integer.compare(a[0], b[0]) : Integer.compare(a[1], b[1]));
int intervalIndex = 0;
for (int queryIndex : queryOrder) {
int query = queries[queryIndex];
while (intervalIndex < intervals.length && intervals[intervalIndex][0] <= query) {
int left = intervals[intervalIndex][0];
int right = intervals[intervalIndex][1];
candidates.offer(new int[] {right - left + 1, right});
intervalIndex++;
}
while (!candidates.isEmpty() && candidates.peek()[1] < query) {
candidates.poll();
}
if (!candidates.isEmpty()) {
result[queryIndex] = candidates.peek()[0];
}
}
return result;
}
}C++Tested in our runner
#include <algorithm>
#include <queue>
#include <utility>
using namespace std;
class Solution {
public:
vector<int> minInterval(vector<vector<int>>& intervals, vector<int>& queries) {
sort(intervals.begin(), intervals.end(), [](const vector<int>& a, const vector<int>& b) {
return a[0] < b[0];
});
vector<pair<int, int>> orderedQueries;
orderedQueries.reserve(queries.size());
for (int i = 0; i < static_cast<int>(queries.size()); ++i) {
orderedQueries.push_back({queries[i], i});
}
sort(orderedQueries.begin(), orderedQueries.end());
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> candidates;
vector<int> answer(queries.size(), -1);
int intervalIndex = 0;
for (const auto& query : orderedQueries) {
int value = query.first;
while (intervalIndex < static_cast<int>(intervals.size()) && intervals[intervalIndex][0] <= value) {
int left = intervals[intervalIndex][0];
int right = intervals[intervalIndex][1];
candidates.push({right - left + 1, right});
++intervalIndex;
}
while (!candidates.empty() && candidates.top().second < value) {
candidates.pop();
}
if (!candidates.empty()) {
answer[query.second] = candidates.top().first;
}
}
return answer;
}
};JavaScriptTested in our runner
/**
* @param {number[][]} intervals
* @param {number[]} queries
* @return {number[]}
*/
var minInterval = function(intervals, queries) {
const sorted = intervals.slice().sort((a, b) => a[0] - b[0]);
const order = queries.map((_, i) => i).sort((a, b) => queries[a] - queries[b]);
const result = new Array(queries.length).fill(-1);
const heap = [];
const less = (a, b) => a[0] < b[0] || (a[0] === b[0] && a[1] < b[1]);
const push = (item) => {
heap.push(item);
let i = heap.length - 1;
while (i > 0) {
const parent = (i - 1) >> 1;
if (!less(heap[i], heap[parent])) break;
[heap[i], heap[parent]] = [heap[parent], heap[i]];
i = parent;
}
};
const pop = () => {
const top = heap[0];
const last = heap.pop();
if (heap.length > 0) {
heap[0] = last;
let i = 0;
while (true) {
const leftChild = 2 * i + 1;
const rightChild = leftChild + 1;
let smallest = i;
if (leftChild < heap.length && less(heap[leftChild], heap[smallest])) smallest = leftChild;
if (rightChild < heap.length && less(heap[rightChild], heap[smallest])) smallest = rightChild;
if (smallest === i) break;
[heap[i], heap[smallest]] = [heap[smallest], heap[i]];
i = smallest;
}
}
return top;
};
let next = 0;
for (const qi of order) {
const q = queries[qi];
while (next < sorted.length && sorted[next][0] <= q) {
const [l, r] = sorted[next];
push([r - l + 1, r]);
next++;
}
while (heap.length > 0 && heap[0][1] < q) {
pop();
}
if (heap.length > 0) {
result[qi] = heap[0][0];
}
}
return result;
};GoTested in our runner
import (
"container/heap"
"sort"
)
type candidateHeap [][2]int
func (h candidateHeap) Len() int { return len(h) }
func (h candidateHeap) Less(i, j int) bool {
if h[i][0] != h[j][0] {
return h[i][0] < h[j][0]
}
return h[i][1] < h[j][1]
}
func (h candidateHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *candidateHeap) Push(x interface{}) {
*h = append(*h, x.([2]int))
}
func (h *candidateHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[:n-1]
return x
}
func minInterval(intervals [][]int, queries []int) []int {
sorted := make([][]int, len(intervals))
copy(sorted, intervals)
sort.Slice(sorted, func(a, b int) bool { return sorted[a][0] < sorted[b][0] })
order := make([]int, len(queries))
for i := range order {
order[i] = i
}
sort.Slice(order, func(a, b int) bool { return queries[order[a]] < queries[order[b]] })
result := make([]int, len(queries))
for i := range result {
result[i] = -1
}
h := &candidateHeap{}
next := 0
for _, qi := range order {
q := queries[qi]
for next < len(sorted) && sorted[next][0] <= q {
l, r := sorted[next][0], sorted[next][1]
heap.Push(h, [2]int{r - l + 1, r})
next++
}
for h.Len() > 0 && (*h)[0][1] < q {
heap.Pop(h)
}
if h.Len() > 0 {
result[qi] = (*h)[0][0]
}
}
return result
}C#Tested in our runner
public class Solution {
public int[] minInterval(int[][] intervals, int[] queries) {
int[][] sorted = (int[][])intervals.Clone();
Array.Sort(sorted, (a, b) => a[0].CompareTo(b[0]));
int[] order = Enumerable.Range(0, queries.Length).ToArray();
Array.Sort(order, (a, b) => queries[a].CompareTo(queries[b]));
int[] result = new int[queries.Length];
Array.Fill(result, -1);
PriorityQueue<int[], int> candidates = new PriorityQueue<int[], int>();
int next = 0;
foreach (int qi in order) {
int q = queries[qi];
while (next < sorted.Length && sorted[next][0] <= q) {
int l = sorted[next][0];
int r = sorted[next][1];
int size = r - l + 1;
candidates.Enqueue(new int[] { size, r }, size);
next++;
}
while (candidates.Count > 0 && candidates.Peek()[1] < q) {
candidates.Dequeue();
}
if (candidates.Count > 0) {
result[qi] = candidates.Peek()[0];
}
}
return result;
}
}Common mistakes
while next < len(sorted) and sorted[next][0] < quses a strict comparison. It misses an interval that starts exactly at the query, such as[5,5]for query 5. Use<=.if candidates[0][1] < querywith anifinstead of awhile. After one expired top is removed, the next top can also be expired and would leave a stale size as the answer. Loop until the top is valid.- Removing entries with
right <= query. An interval that ends exactly at the query still covers it, so onlyright < queryshould be popped. - Writing
result[k]wherekis the position in the sorted order. The answers come back in sorted order instead of input order. Write to the stored original index. - Computing the size as
r - l. The interval[5,5]then gets size 0 instead of 1. The size isr - l + 1. - In the brute force, starting
bestat -1 and then callingbest = min(best, size). The -1 stays the minimum and every answer becomes -1. Check for the sentinel before comparing.
Edge cases
- A single point interval
[5,5]with queries 4, 5, and 6. Expected output is -1, 1, -1, which tests both boundaries. - Duplicate queries such as
[5,5,4,6]. Both copies of 5 must get the same answer at their own positions. - Nested intervals such as
[1,10]and[4,5]with query 4. The inner interval has size 2 and must win over size 10. - A query below every left endpoint or above every right endpoint. The heap empties during cleanup, and the answer is -1.
- Maximum values with
l = 1andr = 10^7. The size is 10^7, which fits in a 32-bit signed integer. - Two intervals of equal size that both cover a query, such as
[1,3]and[2,4]with query 3. Either size works, and the answer is 3.
Follow-ups interviewers ask
- What if intervals is already sorted by left endpoint?
- You can skip the interval sort, which removes one O(n log n) step from the code. The heap work still costs O(n log n) in the worst case, so the overall bound stays O(n log n + m log m). The saving is a constant factor.
- What if the values go up to 10^9 and cannot be used as array indices?
- The sweep never indexes by value. It only compares values and moves a pointer through sorted lists, so the range does not matter. A segment tree approach would need coordinate compression, but the heap sweep does not.
- What if the intervals do not fit in memory?
- Use an external sort on the intervals by left endpoint and on the queries by value. Then make one pass over both sorted streams, with the heap holding only the intervals that cover the current query. In the worst case that heap still holds n entries, so memory depends on how many intervals overlap.
Minimum Interval to Include Each Query FAQ
What is the time complexity of Minimum Interval to Include Each Query?
The sorted heap sweep runs in O(n log n + m log m) time, where n is the number of intervals and m is the number of queries. The brute force runs in O(n * m) time. The sorting steps dominate the cost of the sweep.
Why use a min-heap for Minimum Interval to Include Each Query?
The sweep needs the smallest active interval after each query. A min-heap returns that smallest size at the top, and each push or pop costs O(log n). Expired intervals are removed only when they reach the top, which keeps the cleanup cheap.
Can Minimum Interval to Include Each Query be solved in O(1) extra space?
Not with this sweep. The sweep needs the queries in sorted order along with their original positions, which takes O(m) extra space, and the heap takes O(n). Reordering the queries in place would lose their original positions unless you store them elsewhere.
Why do the queries need their original indices?
The output must match the input order, including duplicate queries. Sorting changes the processing order, so each answer has to be written to the index the query had in the input array.
Why not use dynamic programming or two pointers for this problem?
Neither fits the structure here. The answer depends on which intervals cover each value, and no pair of pointers moves through the intervals in a way that finds the smallest covering size for every query.
Asked at
See which companies ask this — Pro
Related problems
- IPO · same technique: Scheduling / Minimum Cost (Greedy with Priority Queue)
- Meeting Rooms III · same technique: Scheduling / Minimum Cost (Greedy with Priority Queue)
- Minimum Cost to Hire K Workers · same technique: Scheduling / Minimum Cost (Greedy with Priority Queue)
- Meeting Rooms II · same technique: Scheduling / Minimum Cost (Greedy with Priority Queue)
- Reorganize String · same technique: Scheduling / Minimum Cost (Greedy with Priority Queue)
- Merge k Sorted Lists · same pattern: Heap (Priority Queue) Patterns
- Find Median from Data Stream · same pattern: Heap (Priority Queue) Patterns
- Smallest Range Covering Elements from K Lists · same pattern: Heap (Priority Queue) Patterns
- Finding MK Average · same pattern: Heap (Priority Queue) Patterns
- Top K Frequent Elements · same pattern: Heap (Priority Queue) Patterns