Find the minimum range size that contains the given element for Q queries
Given an array Intervals consisting of N pairs of integers where each pair is denoting the value range [L, R]. Also, given an integer array Q consisting of M queries. For each query, the task is to find the size of the smallest range that contains that element. Return -1 if no valid interval exists.
Input: Intervals = [[1, 4], [2, 3], [3, 6], [9, 25], [7, 15], [4, 4]]
Q = [7, 50, 2]
Output: [9, -1, 2]
Explanation: Element 7 is in the range [7, 15] only therefore, the answer will be 15 – 7 + 1 = 9. Element 50 is in no range. Therefore, the answer will be -1.
Similarly, element 2 is in the range [2, 3] and [1, 4] but the smallest range is [2, 3] therefore, the answer will be 3-2+1 = 2.
Input: Intervals = [[1, 4], [2, 4], [3, 6]]
Q = [2, 3]
Output: [3, 3]
Naive Approach: The simplest approach to solve the problem is to Iterate through the array range and for each query find the smallest range that contains the given elements.
Time Complexity: O(N×M)
Auxiliary Space: O(M)
Efficient Approach: The approach mentioned above can be optimized further by using priority_queue. Follow the steps below to solve the problem:
- Initialize a vector of vectors, say Queries and insert all the queries in the array Q along with its index.
- Sort the vector Intervals and Queries using the default sorting function of the vector.
- Initialize a priority_queue, say pq with key as the size of Interval and value as right bound of the range.
- Initialize a vector, say result that will store the size of minimum range for each query.
- Initialize an integer variable, say i that will keep the track of traversed elements of the array Intervals.
- Iterate in the range [0, M-1] using the variable j and perform the following steps:
- Iterate while i < Intervals.size() and Intervals[i] <= Queries[j], insert -(Intervals[i] – Intervals[i] + 1), Intervals[i] as pair and increment the value of i by 1.
- Now remove all the elements from the priority_queue pq with the right element less than Queries[j].
- If the size of priority_queue pq>0, then modify the value of result[Queries[j]] as pq.top().
- Return the array res as the answer.
Below is the implementation of the above approach:
9 -1 2 2 1 9
Time Complexity: O(NlogN+MlogM)
Auxiliary Space: O(N+M)