AlgoInsight

DSA problem

Minimum Interval to Include Each Query

HardLine SweepPattern: Line Sweeptop600AmazonGoogleMicrosoftBloombergApple

You are given a 2D integer array intervals, where intervals[i] = [left_i, right_i] describes the i-th interval starting at left_i and ending at right_i (both inclusive). The size of an interval is right_i - left_i + 1. You are also given an integer array queries. The answer to the j-th query is the size of the smallest interval such that left_i <= queries[j] <= right_i. If no such interval exists, the answer is -1. Return an array containing the answer for each query in the original order.

A brute force solution scans every interval for every query, costing O(m * n) which is far too slow when both arrays approach 10^5 elements. The crucial insight is that we can decouple the order: queries can be sorted and answered offline, then mapped back to their original positions.

Sort the intervals by left endpoint and sort the queries in ascending order. Walk a pointer through the intervals; for each query q, push every interval with left <= q into a min-heap keyed by interval size, storing the right endpoint alongside it. Before reading the answer, pop any heap entries whose right endpoint is strictly less than q — those intervals have already ended and cannot contain the query.

After purging, the heap top is the smallest interval still covering q, or -1 if the heap is empty. Each interval is pushed and popped at most once, so the total heap work is O(n log n). Combined with sorting and binding answers back to original query indices, the overall complexity is O((n + m) log (n + m)) time and O(n) space.

Examples

Example 1
Input: intervals = [[1,4],[2,4],[3,6],[4,4]], queries = [2,3,4,5]
Output: [3,3,1,4]
Explanation: For query 2, smallest covering interval is [2,4] of size 3. For 3, smallest is [2,4] size 3. For 4, the singleton [4,4] of size 1 wins. For 5, only [3,6] of size 4 covers it.
Example 2
Input: intervals = [[2,3],[2,5],[1,8],[20,25]], queries = [2,19,5,22]
Output: [2,-1,4,6]
Explanation: Query 2 is covered by [2,3] of size 2. Query 19 lies in no interval, so -1. Query 5 is covered by [2,5] size 4. Query 22 is covered by [20,25] size 6.
Example 3
Input: intervals = [[1,4]], queries = [0,5]
Output: [-1,-1]
Explanation: Neither query falls inside the only interval, so both answers are -1.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

line-sweepheapsortingbinary-search

Browse all DSA problems