Minimum Interval to Include Each Query

For each query, return the length of the shortest interval containing it — offline sweep with a min-heap.

Hard
Time O((n + q) log (n + q)) Space O(n + q)
LeetCode
7 min read
intervals heap offline

Problem#

Given intervals and queries, for each q, return the size (end - start + 1) of the smallest interval containing q, or -1.

Examples#

  • intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5][3,3,1,4]

Constraints#

  • 1 <= intervals.length, queries.length <= 10^5.

Hints#

Hint 1
Sort intervals by start and queries ascending; activate intervals as their start ≤ q; pop expired tops.

Approach#

Sort queries by value (remember original order). Sort intervals by start. Sweep queries in order; for each query, push every interval starting ≤ q into a min-heap keyed by size; pop heap tops with end < q (expired); the top is the answer.

Solution#

Minimum Interval to Include Each Query
class Solution {
public:
vector<int> minInterval(vector<vector<int>>& intervals, vector<int>& queries) {
sort(intervals.begin(), intervals.end());
vector<pair<int,int>> qs;
for (int i = 0; i < (int)queries.size(); ++i) qs.push_back({queries[i], i});
sort(qs.begin(), qs.end());
priority_queue<tuple<int,int,int>, vector<tuple<int,int,int>>, greater<>> pq;
// (size, start, end), min-heap by size
vector<int> ans(queries.size(), -1);
int i = 0;
for (auto& [q, idx] : qs) {
while (i < (int)intervals.size() && intervals[i][0] <= q) {
int s = intervals[i][0], e = intervals[i][1];
pq.emplace(e - s + 1, s, e);
++i;
}
while (!pq.empty() && get<2>(pq.top()) < q) pq.pop();
if (!pq.empty()) ans[idx] = get<0>(pq.top());
}
return ans;
}
};

Editorial#

Offline (= “answer all queries with rearrangement allowed”) is the key reframing. Sorted queries let us monotonically activate intervals, never deactivating mid-stream — only popping expired ones at the top. Each interval enters and leaves the heap once → O((n + q) log (n + q)).

Complexity#

  • Time: O((n + q) log (n + q)).
  • Space: O(n + q).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.