Find Kth Largest/Smallest element in a Queue
Last Updated :
20 Jul, 2023
Given a queue of integers and an integer K, our task is to write a program that efficiently finds Kth largest/smallest element present in the queue. Return -1 if the number of unique elements inside the queue is less than K.
Examples:
Input: Queue = {15, 27, 18, 13}, K = 2
Output: 18
Explanation: Among 15(front), 27, 18 and 13(back), 18 is the second(Kth) largest.
Input: Queue = {12, 25, 29, 16, 32}, K = 3
Output: 25
Explanation: Among 12(front), 25, 29, 16 and 32(back), 25 is the third(Kth) largest.
Approach: To solve the problem follow the below idea:
The idea to solve the problem is to insert all the queue elements into a set. And then return the K’th largest/smallest element from the set.
Follow the given steps to solve the problem:
- First, check if the size of the queue is less than K. If so, it returns -1, as it is not possible to find the K’th largest/smallest unique element in a queue with less than K elements.
- Now, store every element of the queue into the set st from the queue while popping items from it.
- Now, if K is greater than the size of the set st then return -1, as the total number of unique elements is less than K.
- Create a variable ind for index and initialize it by 1.
- Now traverse over sorted elements in the set st and check if the current element index is equal to K (for smallest) and N+1-K (for largest), where N is the size of the set st.
- If Index matches, return the value at that index.
Below is the implementation of the above approach to find K’th largest:
C++
#include <bits/stdc++.h>
using namespace std;
int kElement(queue< int > q, int K)
{
if (q.size() < K)
return -1;
set< int > st;
while (!q.empty()) {
st.insert(q.front());
q.pop();
}
int N = st.size();
if (N < K)
return -1;
int ind = 1;
for ( auto it = st.begin(); ind <= N; it++) {
if (ind == (N - K + 1))
return *it;
ind++;
}
}
int main()
{
queue< int > q;
q.push(15);
q.push(27);
q.push(18);
q.push(13);
int K = 2;
int kMaxx = kElement(q, K);
cout << "The " << K << "th largest element is " << kMaxx
<< endl;
return 0;
}
|
Java
import java.util.*;
public class GFG {
static int kElement(Queue<Integer> q, int K)
{
if (q.size() < K)
return - 1 ;
TreeSet<Integer> set = new TreeSet<>();
while (!q.isEmpty()) {
set.add(q.peek());
q.poll();
}
if (set.size() < K)
return - 1 ;
int index = 1 ;
for ( int element : set) {
if (index == (set.size() - K + 1 ))
return element;
index++;
}
return - 1 ;
}
public static void main(String[] args)
{
Queue<Integer> q = new LinkedList<>();
q.add( 15 );
q.add( 27 );
q.add( 18 );
q.add( 13 );
int K = 2 ;
int kMaxx = kElement(q, K);
System.out.println(
"The " + K + "th largest element is " + kMaxx);
}
}
|
Python3
from queue import Queue
def kElement(q, K):
if q.qsize() < K:
return - 1
st = set ()
while not q.empty():
st.add(q.queue[ 0 ])
q.get()
N = len (st)
if N < K:
return - 1
ind = 1
for it in sorted (st):
if ind = = (N - K + 1 ):
return it
ind + = 1
if __name__ = = '__main__' :
q = Queue()
q.put( 15 )
q.put( 27 )
q.put( 18 )
q.put( 13 )
K = 2
kMaxx = kElement(q, K)
print ( "The " , K, "th largest element is " , kMaxx, sep = '')
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG {
static int KElement(Queue< int > q, int K)
{
if (q.Count < K)
return -1;
SortedSet< int > st = new SortedSet< int >();
while (q.Count > 0) {
st.Add(q.Peek());
q.Dequeue();
}
int N = st.Count;
if (N < K)
return -1;
int ind = 1;
foreach ( int item in st)
{
if (ind == (N - K + 1))
return item;
ind++;
}
return -1;
}
static void Main()
{
Queue< int > q = new Queue< int >();
q.Enqueue(15);
q.Enqueue(27);
q.Enqueue(18);
q.Enqueue(13);
int K = 2;
int kMaxx = KElement(q, K);
Console.WriteLine(
"The " + K + "th largest element is " + kMaxx);
Console.ReadLine();
}
}
|
Javascript
function kElement(q, K) {
if (q.length < K) {
return -1;
}
const set = new Set();
while (q.length > 0) {
set.add(q.shift());
}
const N = set.size;
if (N < K) {
return -1;
}
let ind = 1;
for (const value of set) {
if (ind === N - K + 1) {
return value;
}
ind++;
}
}
const q = [15, 27, 18, 13];
const K = 2;
const kMaxx = kElement(q, K);
console.log(`The ${K}th largest element is ${kMaxx}`);
|
Output
The 2th largest element is 18
Time Complexity: O(N*logN), to insert all the elements into the set.
Auxiliary Space: O(N), to store all elements into the set.
Share your thoughts in the comments
Please Login to comment...