1851. Minimum Interval to Include Each Query
Hard NeetCode 150 ↗ Open on LeetCode Source: Standard solution only
Quick review
- Pattern
- Intervals
- Time
- O((n + q) log n)
- Space
- O(n + q)
Standard Solution (C++)
SummaryFor each query value, find the size of the smallest interval that contains it, or -1 if none does.
Approach
Key idea: Process queries in increasing order and use a min-heap keyed by interval size. Add intervals as their starts become reachable and lazily drop intervals whose end is already passed.
Steps:
- Sort intervals by start and queries (keeping original indices).
- For each query in ascending order, push all intervals whose start is at most the query as (size, end) into a min-heap.
- Pop intervals whose end is less than the query.
- The heap top, if any, gives the smallest containing interval size.
class Solution {
public:
vector<int> minInterval(vector<vector<int>>& intervals, vector<int>& queries) {
sort(intervals.begin(), intervals.end());
int q = queries.size();
vector<int> order(q);
for (int i = 0; i < q; ++i) order[i] = i;
sort(order.begin(), order.end(), [&](int a, int b) {
return queries[a] < queries[b];
});
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> heap;
vector<int> answer(q, -1);
int idx = 0, n = intervals.size();
for (int qi : order) {
int value = queries[qi];
while (idx < n && intervals[idx][0] <= value) {
int size = intervals[idx][1] - intervals[idx][0] + 1;
heap.push({size, intervals[idx][1]});
++idx;
}
while (!heap.empty() && heap.top().second < value) heap.pop();
if (!heap.empty()) answer[qi] = heap.top().first;
}
return answer;
}
}; Time O((n + q) log n) Space O(n + q)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.