Given an array of intervals arr[] of size N, the task is to find the Kth smallest element among all the elements within the intervals of the given array.
Examples:
_Input : _arr[] = {{5, 11}, {10, 15}, {12, 20}}, K =12
_Output: _13
_Explanation: _Elements in the given array of intervals are: {5, 6, 7, 8, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 17, 18, 19, 20}.
Therefore, the Kth(=12th) smallest element is 13.
_Input: _arr[] = {{5, 11}, {10, 15}, {12, 20}}, K = 7
Output:10
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
**Naive Approach: **The simplest approach is to generate a new array consisting of all the elements from the array of intervals. Sort the new array. Finally, return the Kth smallest element of the array.
Time Complexity: O(X*Log(X)), where **X **is the total number of elements in the intervals.
Auxiliary Space: O(X*log(X))
Efficient approach: To optimize the above approach, the idea is to use MinHeap. Follow the steps below to solve the problem.
Below is the implementation of the above approach:
filter_none
edit
play_arrow
brightness_4
// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
**using**
**namespace**
std;
// Function to get the Kth smallest
// element from an array of intervals
**int**
KthSmallestNum(pair<``**int**``,
**int**``> arr[],
**int**
n,
**int**
k)
{
// Store all the intervals so that it
// returns the minimum element in O(1)
priority_queue<pair<``**int**``,
**int**``>,
vector<pair<``**int**``,
**int**``> >,
greater<pair<``**int**``,
**int**``> > >
pq;
// Insert all Intervals into the MinHeap
**for**
(``**int**
i = 0; i < n; i++) {
pq.push({ arr[i].first,
arr[i].second });
}
// Stores the count of
// popped elements
**int**
cnt = 1;
// Iterate over MinHeap
**while**
(cnt < k) {
// Stores minimum element
// from all remaining intervals
pair<``**int**``,
**int**``> interval
= pq.top();
// Remove minimum element
pq.pop();
// Check if the minimum of the current
// interval is less than the maximum
// of the current interval
**if**
(interval.first < interval.second) {
// Insert new interval
pq.push(
{ interval.first + 1,
interval.second });
}
cnt++;
}
**return**
pq.top().first;
}
// Driver Code
**int**
main()
{
// Intervals given
pair<``**int**``,
**int**``> arr[]
= { { 5, 11 },
{ 10, 15 },
{ 12, 20 } };
// Size of the arr
**int**
n =
**sizeof**``(arr) /
**sizeof**``(arr[0]);
**int**
k = 12;
cout << KthSmallestNum(arr, n, k);
}
#arrays #heap #mathematical #sorting #amazon #amazon-question #min-heap #priority-queue