Problem Description
Given a list of intervals where each interval is defined by its start and end (inclusive), and a list of query integers, determine for each query the size of the smallest interval that contains the query. The size of an interval is measured as (right - left + 1). If no interval contains the query, return -1 for that query.
Key Insights
- Sort the intervals by their start values to efficiently determine when an interval becomes relevant for a given query.
- Process queries in increasing order so that intervals can be added to a data structure (min-heap) as they "start" to cover queries.
- Use a min-heap keyed by the size (length) of the interval to quickly retrieve the smallest interval currently containing the query.
- Remove any intervals from the heap that no longer cover the current query (i.e., their end is less than the query).
- Maintain the original order of queries by storing the indices while sorting.
Space and Time Complexity
Time Complexity: O((N + Q) log N) where N is the number of intervals and Q is the number of queries. Sorting and heap operations dominate the complexity. Space Complexity: O(N + Q) for storing intervals, queries, and the heap.
Solution
The solution uses a two-step approach:
- Sort the queries while keeping track of their original indices.
- Sort intervals by their starting values. For each query (in increasing order), add intervals that start before or at this query to a min-heap, where each entry is the size of the interval along with its end value. Then, remove intervals from the heap that do not cover the query (their end value is less than the query). The heap’s top element (if available) holds the smallest interval size that contains the query.
- Place the answer in a result array at the position corresponding to the original query order.
Data structures used: Sorting arrays and a min-heap for efficient retrieval and removal.