← DSA
HARD

Minimum Interval to Include Each Query

PracticeNeetCode ↗LeetCode ↗

Given a list of intervals and a list of query values, for each query find the size of the smallest interval that contains it (size = end − start + 1). If no interval contains a query, its answer is −1.

Example

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

Key Pointers

Step-by-Step Analysis

  1. Sort intervals by start time; sort query indices by their query value so the original answer order can be restored later.
  2. Maintain a min-heap of (size, end) for intervals that have "started" relative to the current query.
  3. For each query in increasing order, push every interval whose start is at or before the query into the heap.
  4. Pop from the heap while its top interval's end is before the query — those intervals no longer cover it.
  5. If the heap isn't empty, its top's size is the answer for this query; otherwise the answer is −1.
  6. Write results back into the original query order using the saved indices.

Complexity

Time: O((n + q) log n) — Space: O(n + q)

Code

import heapq

def minInterval(intervals: list[list[int]], queries: list[int]) -> list[int]:
    intervals.sort()
    sorted_queries = sorted(range(len(queries)), key=lambda i: queries[i])

    heap = []
    result = [0] * len(queries)
    i = 0

    for qi in sorted_queries:
        q = queries[qi]
        while i < len(intervals) and intervals[i][0] <= q:
            start, end = intervals[i]
            heapq.heappush(heap, (end - start + 1, end))
            i += 1

        while heap and heap[0][1] < q:
            heapq.heappop(heap)

        result[qi] = heap[0][0] if heap else -1

    return result

Code Explanation

How the solution above works, piece by piece.

  1. Sort intervals by start and process queries from smallest to largest (keeping their original positions for the answer).
  2. For each query q, push every interval with start <= q onto a min-heap keyed by size.
  3. Pop intervals whose end is before q; they can't contain this or any later query, so removing them is permanent.
  4. The heap's top is now the smallest interval that contains q, or −1 if the heap is empty.
  5. O((n + q) log n): each interval is pushed and popped once.

Visual Walkthrough

Running it on intervals = [[1, 4], [2, 4], [3, 6], [4, 4]], queries = [2, 3, 4, 5]:

Intervals and the smallest one containing each query[1,4]size 4[2,4]size 3[3,6]size 4[4,4]101234567q = 2 → [2,4] size 3q = 3 → [2,4] size 3q = 4 → [4,4] size 1q = 5 → [3,6] size 4answer [3, 3, 1, 4]
Queries are answered in increasing order. Each time, intervals that have started are added to a min-heap by size, and intervals that already ended before the query are popped. The heap's top is then the smallest interval containing the query.
size-1 interval

Video Explanation

NeetCode — LeetCode 1851