Kth smallest element from an array of intervals
Last Updated :
02 Jul, 2021
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
// 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);
}
Java
// Java program to implement
// the above approach
import java.util.*;
import java.io.*;
class GFG{
// Function to get the Kth smallest
// element from an array of intervals
public static int KthSmallestNum(int arr[][], int n,
int k)
{
// Store all the intervals so that it
// returns the minimum element in O(1)
PriorityQueue<int[]> pq = new PriorityQueue<>(
(a, b) -> a[0] - b[0]);
// Insert all Intervals into the MinHeap
for(int i = 0; i < n; i++)
{
pq.add(new int[]{arr[i][0],
arr[i][1]});
}
// Stores the count of
// popped elements
int cnt = 1;
// Iterate over MinHeap
while (cnt < k)
{
// Stores minimum element
// from all remaining intervals
int[] interval = pq.poll();
// Check if the minimum of the current
// interval is less than the maximum
// of the current interval
if (interval[0] < interval[1])
{
// Insert new interval
pq.add(new int[]{interval[0] + 1,
interval[1]});
}
cnt++;
}
return pq.peek()[0];
}
// Driver Code
public static void main(String args[])
{
// Intervals given
int arr[][] = { { 5, 11 },
{ 10, 15 },
{ 12, 20 } };
// Size of the arr
int n = arr.length;
int k = 12;
System.out.println(KthSmallestNum(arr, n, k));
}
}
// This code is contributed by hemanth gadarla
Python3
# Python3 program to implement
# the above approach
# Function to get the Kth smallest
# element from an array of intervals
def KthSmallestNum(arr, n, k):
# Store all the intervals so that it
# returns the minimum element in O(1)
pq = []
# Insert all Intervals into the MinHeap
for i in range(n):
pq.append([arr[i][0], arr[i][1]])
# Stores the count of
# popped elements
cnt = 1
# Iterate over MinHeap
while (cnt < k):
# Stores minimum element
# from all remaining intervals
pq.sort(reverse = True)
interval = pq[0]
# Remove minimum element
pq.remove(pq[0])
# Check if the minimum of the current
# interval is less than the maximum
# of the current interval
if (interval[0] < interval[1]):
# Insert new interval
pq.append([interval[0] + 1,
interval[1]])
cnt += 1
pq.sort(reverse = True)
return pq[0][0] + 1
# Driver Code
if __name__ == '__main__':
# Intervals given
arr = [ [ 5, 11 ],
[ 10, 15 ],
[ 12, 20 ] ]
# Size of the arr
n = len(arr)
k = 12
print(KthSmallestNum(arr, n, k))
# This code is contributed by SURENDRA_GANGWAR
C#
// C# Program to implement
// the above approach
using System;
using System.Collections;
using System.Collections.Generic;
class GFG {
// Function to get the Kth smallest
// element from an array of intervals
static int KthSmallestNum(int[,] arr, int n, int k)
{
// Store all the intervals so that it
// returns the minimum element in O(1)
ArrayList pq = new ArrayList();
// Insert all Intervals into the MinHeap
for(int i = 0; i < n; i++)
{
pq.Add(new Tuple<int,int>(arr[i,0], arr[i,1]));
}
// Stores the count of
// popped elements
int cnt = 1;
// Iterate over MinHeap
while (cnt < k)
{
// Stores minimum element
// from all remaining intervals
pq.Sort();
pq.Reverse();
Tuple<int,int> interval = (Tuple<int,int>)pq[0];
// Remove minimum element
pq.RemoveAt(0);
// Check if the minimum of the current
// interval is less than the maximum
// of the current interval
if (interval.Item1 < interval.Item2)
{
// Insert new interval
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;
}
// Driver code
static void Main()
{
// Intervals given
int[,] arr = { { 5, 11 },
{ 10, 15 },
{ 12, 20 } };
// Size of the arr
int n = arr.GetLength(0);
int k = 12;
Console.WriteLine(KthSmallestNum(arr, n, k));
}
}
// This code is contributed by divyeshrabadiya07
JavaScript
<script>
// JavaScript Program to implement
// the above approach
// Function to get the Kth smallest
// element from an array of intervals
function KthSmallestNum(arr, n, k)
{
// Store all the intervals so that it
// returns the minimum element in O(1)
var pq = [];
// Insert all Intervals into the MinHeap
for(var i = 0; i < n; i++)
{
pq.push([arr[i][0], arr[i][1]]);
}
// Stores the count of
// popped elements
var cnt = 1;
// Iterate over MinHeap
while (cnt < k)
{
// Stores minimum element
// from all remaining intervals
pq.sort((a,b)=>{
if(a[0]==b[0])
return a[1]-b[1]
return a[0]-b[0]
});
var interval = pq[0];
// Remove minimum element
pq.shift();
// Check if the minimum of the current
// interval is less than the maximum
// of the current interval
if (interval[0] < interval[1])
{
// Insert new interval
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];
}
// Driver code
// Intervals given
var arr = [ [ 5, 11 ],
[ 10, 15 ],
[ 12, 20 ] ];
// Size of the arr
var n = arr.length;
var k = 12;
document.write(KthSmallestNum(arr, n, k));
</script>
Time Complexity: O(K*logK)
Auxiliary Space: O(N)
Similar Reads
Find k smallest elements in an array Given an array arr[] and an integer k, the task is to find k smallest elements in the given array. Elements in the output array can be in any order.Examples:Input: arr[] = [1, 23, 12, 9, 30, 2, 50], k = 3Output: [1, 2, 9]Input: arr[] = [11, 5, 12, 9, 44, 17, 2], k = 2Output: [2, 5]Table of Content[A
15 min read
Python heapq to find K'th smallest element in a 2D array Given an n x n matrix and integer k. Find the k'th smallest element in the given 2D array. Examples: Input : mat = [[10, 25, 20, 40], [15, 45, 35, 30], [24, 29, 37, 48], [32, 33, 39, 50]] k = 7 Output : 7th smallest element is 30 We will use similar approach like Kâth Smallest/Largest Element in Uns
3 min read
Find K-th smallest element in an array for multiple queries Given an array arr[] of size N and an array Q[][] consisting of M queries that needs to be processed on the given array. It is known that these queries can be of the following two types: Type 1: If Q = 1, then add an element in the array {type, element_to_add}.Type 2: If Q = 2, then print the K-th s
9 min read
Smallest greater elements in whole array An array is given of n length, and we need to calculate the next greater element for each element in the given array. If the next greater element is not available in the given array then we need to fill '_' at that index place. Examples : Input : 6 3 9 8 10 2 1 15 7 Output : 7 6 10 9 15 3 2 _ 8 Here
11 min read
Floor of every element in same array Given an array of integers, find the closest smaller or same element for every element. If all elements are greater for an element, then print -1. We may assume that the array has at least two elements. Examples: Input : arr[] = {10, 5, 11, 10, 20, 12} Output : 10 -1 10 10 12 11 Note that there are
14 min read
Kâth Smallest Element in Unsorted Array Given an array arr[] of N distinct elements and a number K, where K is smaller than the size of the array. Find the K'th smallest element in the given array. Examples:Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 3 Output: 7Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 4 Output: 10 Table of Content[Naive Ap
15 min read
Find the Kth occurrence of an element in a sorted Array Given a sorted array arr[] of size N, an integer X, and a positive integer K, the task is to find the index of Kth occurrence of X in the given array. Examples: Input: N = 10, arr[] = [1, 2, 3, 3, 4, 5, 5, 5, 5, 5], X = 5, K = 2Output: Starting index of the array is '0' Second occurrence of 5 is at
15+ min read
Find the Kth smallest element in the sorted generated array Given an array arr[] of N elements and an integer K, the task is to generate an B[] with the following rules: Copy elements arr[1...N], N times to array B[].Copy elements arr[1...N/2], 2*N times to array B[].Copy elements arr[1...N/4], 3*N times to array B[].Similarly, until only no element is left
8 min read
Find frequency of smallest value in an array Given an array A of N elements. Find the frequency of the smallest value in the array. Examples: Input : N = 5, arr[] = {3, 2, 3, 4, 4} Output : 1 The smallest element in the array is 2 and it occurs only once. Input : N = 6, arr[] = {4, 3, 5, 3, 3, 6} Output : 3 The smallest element in the array is
5 min read
k-th smallest absolute difference of two elements in an array We are given an array of size n containing positive integers. The absolute difference between values at indices i and j is |a[i] - a[j]|. There are n*(n-1)/2 such pairs and we are asked to print the kth (1 <= k <= n*(n-1)/2) as the smallest absolute difference among all these pairs. Examples:
9 min read