Minimum Interval to Include Each Query
Difficulty: Hard · Pattern: Intervals · LeetCode #1851
intervals[i] = [left, right] has size right − left + 1. For each query q, return the size of the smallest interval containing q, or -1 if none does.
Examples
text
intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5] → [3,3,1,4]
intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22] → [2,-1,4,6]Hints
- Answer the queries offline: sort them, then answer in that order and put each answer back at the query's original index.
- As q increases, more intervals have started (add them) and some have ended (they can be dropped lazily).
Approach
- Sort
intervalsby left. Sort the query indices by query value. - Keep a min-heap of
(size, right). For each query q in increasing order:- Push every interval with
left ≤ q. - Pop from the top while
right < q. Those intervals ended before q, and since queries only increase they'll never matter again. - The answer is the heap top's size, or −1 if the heap is empty.
- Push every interval with
Lazy deletion works because we only need the top to be valid. O((n + q) log n). The offline sort + sweep technique is the key interview insight.
Complexity
Time: O((n + q) log n + q log q). Space: O(n + q).
Python solution
import heapq
def minInterval(intervals, queries):
intervals = sorted(intervals)
ans = [-1] * len(queries)
heap, i = [], 0
for qi in sorted(range(len(queries)), key=lambda k: queries[k]):
q = queries[qi]
while i < len(intervals) and intervals[i][0] <= q:
l, r = intervals[i]
heapq.heappush(heap, (r - l + 1, r))
i += 1
while heap and heap[0][1] < q:
heapq.heappop(heap)
if heap:
ans[qi] = heap[0][0]
return ansJavaScript solution
function minInterval(intervals, queries) {
const iv = [...intervals].sort((a, b) => a[0] - b[0]);
const order = [...queries.keys()].sort((a, b) => queries[a] - queries[b]);
const ans = new Array(queries.length).fill(-1), heap = [];
const less = (a, b) => a[0] < b[0] || (a[0] === b[0] && a[1] < b[1]);
const push = (x) => { heap.push(x); let i = heap.length - 1; while (i > 0) { const p = (i - 1) >> 1; if (!less(heap[i], heap[p])) break; [heap[i], heap[p]] = [heap[p], heap[i]]; i = p; } };
const pop = () => { const last = heap.pop(); if (heap.length) { heap[0] = last; let i = 0; for (;;) { const l = 2 * i + 1, r = l + 1; let m = i; if (l < heap.length && less(heap[l], heap[m])) m = l; if (r < heap.length && less(heap[r], heap[m])) m = r; if (m === i) break; [heap[i], heap[m]] = [heap[m], heap[i]]; i = m; } } };
let i = 0;
for (const qi of order) {
const q = queries[qi];
while (i < iv.length && iv[i][0] <= q) { push([iv[i][1] - iv[i][0] + 1, iv[i][1]]); i++; }
while (heap.length && heap[0][1] < q) pop();
if (heap.length) ans[qi] = heap[0][0];
}
return ans;
}