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
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read