Minimum Interval to Include Each Query

Hard · Trees · Array · Binary Search · Line Sweep · Sorting · Heap (Priority Queue)

Problem

You are given a list of closed intervals intervals[i] = [left_i, right_i]. The size of an interval is right_i - left_i + 1, the number of integers it contains. You are also given an array queries.

For each queries[j], find the smallest-size interval i with left_i <= queries[j] <= right_i and report its size, or -1 if no interval contains the query. Return the answers as an array in the same order as queries.

Examples

Input: intervals = [[1,6],[3,4],[8,8]], queries = [3,5,8,7]
Output: [2,6,1,-1]

3 is inside [3,4] (size 2); 5 only fits [1,6] (size 6); 8 fits [8,8] (size 1); 7 fits nothing.

Input: intervals = [[2,9]], queries = [1,9]
Output: [-1,8]

1 is left of the interval; 9 is its right end, and ends count.

Input: intervals = [[1,10],[2,9],[4,5]], queries = [4,2,10]
Output: [2,8,10]

4 is in all three, the smallest is [4,5] (size 2); 2 is in [2,9] (size 8); 10 only in [1,10].

Constraints

Approaches

Follow-up

If queries had to be answered online, one at a time in the given order, you could compress coordinates and build a segment tree that stores, for each point, the smallest size of an interval covering it (range "chmin" updates, point queries). That is O((n + q) log(n + q)) as well, without reordering queries.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…