Given an array arr[] consisting of N integers and an integer K, the task is to find the Kth smallest element in the array using Priority Queue.
Examples:
Input: arr[] = {5, 20, 10, 7, 1}, N = 5, K = 2
Output: 5
Explanation: In the given array, the 2nd smallest element is 5. Therefore, the required output is 5.
Input: arr[] = {5, 20, 10, 7, 1}, N = 5, K = 5
Output: 20
Explanation: In the given array, the 5th smallest element is 20. Therefore, the required output is 20.
Approach: The idea is to use PriorityQueue Collection in Java or priority_queue STL library to implement Max_Heap to find the Kth smallest array element. Follow the steps below to solve the problem:
- Implement Max Heap using a priority_queue.
- Push first K array elements into the priority_queue.
- From there on, after every insertion of an array element, pop the element at the top of the priority_queue.
- After complete traversal of the array, print the element at the top of the priority queue as the required answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void kthSmallest(vector< int >& v, int N, int K)
{
priority_queue< int > heap1;
for ( int i = 0; i < N; ++i) {
heap1.push(v[i]);
if (heap1.size() > K) {
heap1.pop();
}
}
cout << heap1.top() << endl;
}
int main()
{
vector< int > vec = { 5, 20, 10, 7, 1 };
int N = vec.size();
int K = 2;
kthSmallest(vec, N, K % (N+1));
return 0;
}
|
Java
import java.util.*;
class CustomComparator implements Comparator<Integer> {
@Override
public int compare(Integer number1, Integer number2) {
int value = number1.compareTo(number2);
if (value > 0 ) {
return - 1 ;
}
else if (value < 0 ) {
return 1 ;
}
else {
return 0 ;
}
}
}
class GFG{
static void kthSmallest( int []v, int N, int K)
{
PriorityQueue<Integer> heap1 = new PriorityQueue<Integer>( new CustomComparator());
for ( int i = 0 ; i < N; ++i) {
heap1.add(v[i]);
if (heap1.size() > K) {
heap1.remove();
}
}
System.out.print(heap1.peek() + "\n" );
}
public static void main(String[] args)
{
int []vec = { 5 , 20 , 10 , 7 , 1 };
int N = vec.length;
int K = 2 ;
kthSmallest(vec, N, K % N);
}
}
|
Python3
def kthSmallest(v, N, K):
heap1 = []
for i in range (N):
heap1.append(v[i])
if ( len (heap1) > K):
heap1.sort()
heap1.reverse()
del heap1[ 0 ]
heap1.sort()
heap1.reverse()
print (heap1[ 0 ])
vec = [ 5 , 20 , 10 , 7 , 1 ]
N = len (vec)
K = 2
kthSmallest(vec, N, K % N)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static void kthSmallest( int []v, int N, int K)
{
List< int > heap1 = new List< int >();
for ( int i = 0; i < N; ++i) {
heap1.Add(v[i]);
if (heap1.Count > K) {
heap1.Sort();
heap1.Reverse();
heap1.RemoveAt(0);
}
}
heap1.Sort();
heap1.Reverse();
Console.WriteLine(heap1[0]);
}
public static void Main(String[] args)
{
int []vec = { 5, 20, 10, 7, 1 };
int N = vec.Length;
int K = 2;
kthSmallest(vec, N, K % N);
}
}
|
Javascript
<script>
function kthSmallest(v,N,K)
{
let heap1 = [];
for (let i = 0; i < N; ++i) {
heap1.push(v[i]);
if (heap1.length > K)
{
heap1.sort( function (a,b){
return a-b;
});
heap1.reverse();
heap1.shift();
}
}
heap1.sort( function (a,b){
return a-b;
});
heap1.reverse();
document.write(heap1[0] + "<br>" );
}
let vec=[5, 20, 10, 7, 1 ];
let N = vec.length;
let K = 2;
kthSmallest(vec, N, K % N);
</script>
|
Time Complexity: O(N LogK)
Auxiliary Space: O(K), since the priority queue at any time holds at max k elements.
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!