![]() |
VOOZH | about |
Given n ranges of the form [l, r] and an integer q denoting the number of queries. The task is to return the kth smallest element for each query (assume k>1) after combining all the ranges. In case the kth smallest element doesn't exist, return -1.
Examples :
Input: n = 2, q = 3, range[] = {{1, 4}, {6, 8}}, queries[] = {2, 6, 10}
Output: 2 7 -1
Explanation: After combining the given ranges, the numbers become 1 2 3 4 6 7 8. As here 2nd smallest element is 2, 6th smallest element is 7, and as 10th element doesn't exist, so we return -1.Input : arr[] = {{2, 6}, {5, 7}} queries[] = {5, 8};
Output : 6, -1
Explanation: After combining the given ranges, the numbers become 2 3 4 5 6 7. As here 5th element is 6, 8th element doesn't exist, so we return -1.
The idea is to Merge Overlapping Intervals and keep all intervals sorted in ascending order of start time. After merging in an array merged[], we use linear search to find the kth smallest element.
6 -1
Time Complexity : O(nlog(n) + qn) - O(nlog(n)) arises from the sorting and merging operations performed on the intervals and O(qn) is to process the q number of queries where each query taken O(n) time.
Auxiliary Space: O(n) - for storing the input intervals arr[].
We first sort and merge the range intervals. Then, by storing the prefix sum of element counts in each range, we can use binary search to quickly find the kth smallest element.
For Example: For the range { {1 4}, {6 8}, {9 10} } the number of elements in each range are : 4, 3, 2 respectively. Hence, prefix sum set would store {4 7 9}.
For kth smallest element we just have to find the lower_bound of k in set. the corresponding index will give us the index of the merged interval in which the required element is stored.
This reduces the search time for each query from O(n) to O(log n), making it much faster for large datasets.
2 7 -1
Time Complexity : O(nlog(n) + qlog(n)) : O(nlogn) due to insertion operation in a set performed on n intervals and qlog(n) is to perform the q number of queries. Where each query taken long time.
Auxiliary Space: O(n) - to store the prefix sum of element counts.