Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
You are given a 2D integer array intervals, where intervals[i] = [lefti, righti] describes the ith interval starting at lefti and ending at righti (inclusive). The size of an interval is defined as the number of integers it contains, or more formally righti - lefti + 1.
You are also given an integer array queries. The answer to the jth query is the size of the smallest interval i such that lefti <= queries[j] <= righti. If no such interval exists, the answer is -1.
Return an array containing the answers to the queries.
Example 1:
Input: intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5] Output: [3,3,1,4] Explanation: The queries are processed as follows: - Query = 2: The interval [2,4] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3. - Query = 3: The interval [2,4] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3. - Query = 4: The interval [4,4] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1. - Query = 5: The interval [3,6] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4.
Example 2:
Input: intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22] Output: [2,-1,4,6] Explanation: The queries are processed as follows: - Query = 2: The interval [2,3] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2. - Query = 19: None of the intervals contain 19. The answer is -1. - Query = 5: The interval [2,5] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4. - Query = 22: The interval [20,25] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6.
Constraints:
1 <= intervals.length <= 1051 <= queries.length <= 105intervals[i].length == 21 <= lefti <= righti <= 1071 <= queries[j] <= 107Problem summary: You are given a 2D integer array intervals, where intervals[i] = [lefti, righti] describes the ith interval starting at lefti and ending at righti (inclusive). The size of an interval is defined as the number of integers it contains, or more formally righti - lefti + 1. You are also given an integer array queries. The answer to the jth query is the size of the smallest interval i such that lefti <= queries[j] <= righti. If no such interval exists, the answer is -1. Return an array containing the answers to the queries.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Binary Search
[[1,4],[2,4],[3,6],[4,4]] [2,3,4,5]
[[2,3],[2,5],[1,8],[20,25]] [2,19,5,22]
number-of-flowers-in-full-bloom)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1851: Minimum Interval to Include Each Query
class Solution {
public int[] minInterval(int[][] intervals, int[] queries) {
int n = intervals.length, m = queries.length;
Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
int[][] qs = new int[m][0];
for (int i = 0; i < m; ++i) {
qs[i] = new int[] {queries[i], i};
}
Arrays.sort(qs, (a, b) -> a[0] - b[0]);
int[] ans = new int[m];
Arrays.fill(ans, -1);
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
int i = 0;
for (int[] q : qs) {
while (i < n && intervals[i][0] <= q[0]) {
int a = intervals[i][0], b = intervals[i][1];
pq.offer(new int[] {b - a + 1, b});
++i;
}
while (!pq.isEmpty() && pq.peek()[1] < q[0]) {
pq.poll();
}
if (!pq.isEmpty()) {
ans[q[1]] = pq.peek()[0];
}
}
return ans;
}
}
// Accepted solution for LeetCode #1851: Minimum Interval to Include Each Query
func minInterval(intervals [][]int, queries []int) []int {
n, m := len(intervals), len(queries)
sort.Slice(intervals, func(i, j int) bool { return intervals[i][0] < intervals[j][0] })
qs := make([][2]int, m)
ans := make([]int, m)
for i := range qs {
qs[i] = [2]int{queries[i], i}
ans[i] = -1
}
sort.Slice(qs, func(i, j int) bool { return qs[i][0] < qs[j][0] })
pq := hp{}
i := 0
for _, q := range qs {
x, j := q[0], q[1]
for i < n && intervals[i][0] <= x {
a, b := intervals[i][0], intervals[i][1]
heap.Push(&pq, pair{b - a + 1, b})
i++
}
for len(pq) > 0 && pq[0].r < x {
heap.Pop(&pq)
}
if len(pq) > 0 {
ans[j] = pq[0].v
}
}
return ans
}
type pair struct{ v, r int }
type hp []pair
func (h hp) Len() int { return len(h) }
func (h hp) Less(i, j int) bool { return h[i].v < h[j].v }
func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *hp) Push(v any) { *h = append(*h, v.(pair)) }
func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
# Accepted solution for LeetCode #1851: Minimum Interval to Include Each Query
class Solution:
def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]:
n, m = len(intervals), len(queries)
intervals.sort()
queries = sorted((x, i) for i, x in enumerate(queries))
ans = [-1] * m
pq = []
i = 0
for x, j in queries:
while i < n and intervals[i][0] <= x:
a, b = intervals[i]
heappush(pq, (b - a + 1, b))
i += 1
while pq and pq[0][1] < x:
heappop(pq)
if pq:
ans[j] = pq[0][0]
return ans
// Accepted solution for LeetCode #1851: Minimum Interval to Include Each Query
/**
* [1851] Minimum Interval to Include Each Query
*
* You are given a 2D integer array intervals, where intervals[i] = [lefti, righti] describes the i^th interval starting at lefti and ending at righti (inclusive). The size of an interval is defined as the number of integers it contains, or more formally righti - lefti + 1.
* You are also given an integer array queries. The answer to the j^th query is the size of the smallest interval i such that lefti <= queries[j] <= righti. If no such interval exists, the answer is -1.
* Return an array containing the answers to the queries.
*
* Example 1:
*
* Input: intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5]
* Output: [3,3,1,4]
* Explanation: The queries are processed as follows:
* - Query = 2: The interval [2,4] is the smallest interval containing 2. The answer is 4 - 2 + 1 = 3.
* - Query = 3: The interval [2,4] is the smallest interval containing 3. The answer is 4 - 2 + 1 = 3.
* - Query = 4: The interval [4,4] is the smallest interval containing 4. The answer is 4 - 4 + 1 = 1.
* - Query = 5: The interval [3,6] is the smallest interval containing 5. The answer is 6 - 3 + 1 = 4.
*
* Example 2:
*
* Input: intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22]
* Output: [2,-1,4,6]
* Explanation: The queries are processed as follows:
* - Query = 2: The interval [2,3] is the smallest interval containing 2. The answer is 3 - 2 + 1 = 2.
* - Query = 19: None of the intervals contain 19. The answer is -1.
* - Query = 5: The interval [2,5] is the smallest interval containing 5. The answer is 5 - 2 + 1 = 4.
* - Query = 22: The interval [20,25] is the smallest interval containing 22. The answer is 25 - 20 + 1 = 6.
*
*
* Constraints:
*
* 1 <= intervals.length <= 10^5
* 1 <= queries.length <= 10^5
* intervals[i].length == 2
* 1 <= lefti <= righti <= 10^7
* 1 <= queries[j] <= 10^7
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/minimum-interval-to-include-each-query/
// discuss: https://leetcode.com/problems/minimum-interval-to-include-each-query/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn min_interval(intervals: Vec<Vec<i32>>, queries: Vec<i32>) -> Vec<i32> {
vec![]
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_1851_example_1() {
let intervals = vec![vec![1, 4], vec![2, 4], vec![3, 6], vec![4, 4]];
let queries = vec![2, 3, 4, 5];
let result = vec![3, 3, 1, 4];
assert_eq!(Solution::min_interval(intervals, queries), result);
}
#[test]
#[ignore]
fn test_1851_example_2() {
let intervals = vec![vec![2, 3], vec![2, 5], vec![1, 8], vec![20, 25]];
let queries = vec![2, 19, 5, 22];
let result = vec![2, -1, 4, 6];
assert_eq!(Solution::min_interval(intervals, queries), result);
}
}
// Accepted solution for LeetCode #1851: Minimum Interval to Include Each Query
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1851: Minimum Interval to Include Each Query
// class Solution {
// public int[] minInterval(int[][] intervals, int[] queries) {
// int n = intervals.length, m = queries.length;
// Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
// int[][] qs = new int[m][0];
// for (int i = 0; i < m; ++i) {
// qs[i] = new int[] {queries[i], i};
// }
// Arrays.sort(qs, (a, b) -> a[0] - b[0]);
// int[] ans = new int[m];
// Arrays.fill(ans, -1);
// PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
// int i = 0;
// for (int[] q : qs) {
// while (i < n && intervals[i][0] <= q[0]) {
// int a = intervals[i][0], b = intervals[i][1];
// pq.offer(new int[] {b - a + 1, b});
// ++i;
// }
// while (!pq.isEmpty() && pq.peek()[1] < q[0]) {
// pq.poll();
// }
// if (!pq.isEmpty()) {
// ans[q[1]] = pq.peek()[0];
// }
// }
// return ans;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.