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
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.
- Create a MinHeap, say pq to store all the intervals of the given array so that it returns the minimum element among all the elements of remaining intervals in O(1).
- Pop the minimum interval from the MinHeap and check if the minimum element of the popped interval is less than the maximum element of the popped interval. If found to be true, then insert a new interval {minimum element of popped interval + 1, maximum element of the popped interval}.
- Repeat the above step K – 1 times.
- Finally, return the minimum element of the popped interval.
Below is the implementation of the above approach:
C++14
#include <bits/stdc++.h>
using namespace std;
int KthSmallestNum(pair< int , int > arr[],
int n, int k)
{
priority_queue<pair< int , int >,
vector<pair< int , int > >,
greater<pair< int , int > > >
pq;
for ( int i = 0; i < n; i++) {
pq.push({ arr[i].first,
arr[i].second });
}
int cnt = 1;
while (cnt < k) {
pair< int , int > interval
= pq.top();
pq.pop();
if (interval.first < interval.second) {
pq.push(
{ interval.first + 1,
interval.second });
}
cnt++;
}
return pq.top().first;
}
int main()
{
pair< int , int > arr[]
= { { 5, 11 },
{ 10, 15 },
{ 12, 20 } };
int n = sizeof (arr) / sizeof (arr[0]);
int k = 12;
cout << KthSmallestNum(arr, n, k);
}
|
Java
import java.util.*;
import java.io.*;
class GFG{
public static int KthSmallestNum( int arr[][], int n,
int k)
{
PriorityQueue< int []> pq = new PriorityQueue<>(
(a, b) -> a[ 0 ] - b[ 0 ]);
for ( int i = 0 ; i < n; i++)
{
pq.add( new int []{arr[i][ 0 ],
arr[i][ 1 ]});
}
int cnt = 1 ;
while (cnt < k)
{
int [] interval = pq.poll();
if (interval[ 0 ] < interval[ 1 ])
{
pq.add( new int []{interval[ 0 ] + 1 ,
interval[ 1 ]});
}
cnt++;
}
return pq.peek()[ 0 ];
}
public static void main(String args[])
{
int arr[][] = { { 5 , 11 },
{ 10 , 15 },
{ 12 , 20 } };
int n = arr.length;
int k = 12 ;
System.out.println(KthSmallestNum(arr, n, k));
}
}
|
Python3
def KthSmallestNum(arr, n, k):
pq = []
for i in range (n):
pq.append([arr[i][ 0 ], arr[i][ 1 ]])
cnt = 1
while (cnt < k):
pq.sort(reverse = True )
interval = pq[ 0 ]
pq.remove(pq[ 0 ])
if (interval[ 0 ] < interval[ 1 ]):
pq.append([interval[ 0 ] + 1 ,
interval[ 1 ]])
cnt + = 1
pq.sort(reverse = True )
return pq[ 0 ][ 0 ] + 1
if __name__ = = '__main__' :
arr = [ [ 5 , 11 ],
[ 10 , 15 ],
[ 12 , 20 ] ]
n = len (arr)
k = 12
print (KthSmallestNum(arr, n, k))
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
class GFG {
static int KthSmallestNum( int [,] arr, int n, int k)
{
ArrayList pq = new ArrayList();
for ( int i = 0; i < n; i++)
{
pq.Add( new Tuple< int , int >(arr[i,0], arr[i,1]));
}
int cnt = 1;
while (cnt < k)
{
pq.Sort();
pq.Reverse();
Tuple< int , int > interval = (Tuple< int , int >)pq[0];
pq.RemoveAt(0);
if (interval.Item1 < interval.Item2)
{
pq.Add( new Tuple< int , int >(interval.Item1 + 1, interval.Item2));
}
cnt += 1;
}
pq.Sort();
pq.Reverse();
return ((Tuple< int , int >)pq[0]).Item1 + 1;
}
static void Main()
{
int [,] arr = { { 5, 11 },
{ 10, 15 },
{ 12, 20 } };
int n = arr.GetLength(0);
int k = 12;
Console.WriteLine(KthSmallestNum(arr, n, k));
}
}
|
Javascript
<script>
function KthSmallestNum(arr, n, k)
{
var pq = [];
for ( var i = 0; i < n; i++)
{
pq.push([arr[i][0], arr[i][1]]);
}
var cnt = 1;
while (cnt < k)
{
pq.sort((a,b)=>{
if (a[0]==b[0])
return a[1]-b[1]
return a[0]-b[0]
});
var interval = pq[0];
pq.shift();
if (interval[0] < interval[1])
{
pq.push([interval[0] + 1, interval[1]]);
}
cnt += 1;
}
pq.sort((a,b) =>
{
if (a[0]==b[0])
return a[1]-b[1]
return a[0]-b[0]
});
return (pq[0])[0];
}
var arr = [ [ 5, 11 ],
[ 10, 15 ],
[ 12, 20 ] ];
var n = arr.length;
var k = 12;
document.write(KthSmallestNum(arr, n, k));
</script>
|
Time Complexity: O(K*logK)
Auxiliary Space: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!