View on NeetCode
View on LeetCode

Problem

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 <= 10^5
  • 1 <= queries.length <= 10^5
  • intervals[i].length == 2
  • 1 <= lefti <= righti <= 10^7
  • 1 <= queries[j] <= 10^7

Solution

Approach: Sort + Min Heap (Line Sweep)

The key insight is to process queries in sorted order, using a min heap to track valid intervals by size.

Implementation

import heapq

class Solution:
    def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]:
        # Sort intervals by start time
        intervals.sort()

        # Create list of (query, original_index) and sort by query value
        sorted_queries = sorted((q, i) for i, q in enumerate(queries))

        result = [-1] * len(queries)
        min_heap = []  # (size, end)
        interval_idx = 0

        for query, original_idx in sorted_queries:
            # Add all intervals that start before or at query
            while interval_idx < len(intervals) and intervals[interval_idx][0] <= query:
                left, right = intervals[interval_idx]
                size = right - left + 1
                heapq.heappush(min_heap, (size, right))
                interval_idx += 1

            # Remove intervals that end before query
            while min_heap and min_heap[0][1] < query:
                heapq.heappop(min_heap)

            # The smallest valid interval is at top of heap
            if min_heap:
                result[original_idx] = min_heap[0][0]

        return result

Approach 2: With Interval Preprocessing

import heapq

class Solution:
    def minInterval(self, intervals: List[List[int]], queries: List[int]) -> List[int]:
        intervals.sort()
        indexed_queries = sorted((q, i) for i, q in enumerate(queries))

        result = {}
        min_heap = []
        i = 0

        for q, idx in indexed_queries:
            # Add intervals that can contain this query
            while i < len(intervals) and intervals[i][0] <= q:
                left, right = intervals[i]
                heapq.heappush(min_heap, (right - left + 1, right))
                i += 1

            # Remove intervals that end before this query
            while min_heap and min_heap[0][1] < q:
                heapq.heappop(min_heap)

            result[idx] = min_heap[0][0] if min_heap else -1

        return [result[i] for i in range(len(queries))]

Complexity Analysis

  • Time Complexity: O((n + q) log n), where n is number of intervals and q is number of queries. Sorting intervals and queries, plus heap operations.
  • Space Complexity: O(n + q) for heap and result storage.

Key Insights

  1. Sort Both: Sort intervals by start time and queries by value for efficient processing.

  2. Line Sweep: Process queries left to right, maintaining set of active (valid) intervals.

  3. Min Heap by Size: Use min heap ordered by interval size to quickly find smallest valid interval.

  4. Add and Remove: For each query, add newly starting intervals and remove expired intervals.

  5. Original Order: Track original query indices to return results in correct order.

  6. Greedy Selection: The smallest interval that contains a query is always at the top of the min heap (if any valid interval exists).

  7. Efficiency: Processing in sorted order avoids repeatedly checking all intervals for each query.