Open In App

Find Kth Largest/Smallest element in a Queue

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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++
// C++ program to find the Kth largest element
// present in the queue
#include <bits/stdc++.h>
using namespace std;

// Function which return Kth largest element
// of the queue
int kElement(queue<int> q, int K)
{

    // If queue size is less than K
    // then return -1
    if (q.size() < K)
        return -1;

    // Declare SET st
    set<int> st;

    // Loop to insert every element of queue
    // inside set
    while (!q.empty()) {
        // Inserting current front element
        // inside set
        st.insert(q.front());

        // pop current front element
        q.pop();
    }

    // To store set size/length
    int N = st.size();

    // Check if set size is less than K
    if (N < K)
        return -1;

    // Initialize index by 1
    int ind = 1;

    // Loop to find K'th largest element
    for (auto it = st.begin(); ind <= N; it++) {

        // If sorted index is equal to k
        // return element of that index
        if (ind == (N - K + 1))
            return *it;

        // Increment the index by 1
        ind++;
    }
}

// Driver Code
int main()
{
    queue<int> q;

    // Pushing elements into queue
    q.push(15);
    q.push(27);
    q.push(18);
    q.push(13);

    int K = 2;

    // Call function and store return value
    // into kMaxx
    int kMaxx = kElement(q, K);

    // Print the Kth largest element
    cout << "The " << K << "th largest element is " << kMaxx
         << endl;

    return 0;
}
Java
// Java program to find the Kth largest element present
// in the queue
import java.util.*;

public class GFG {
    // Function which returns the Kth largest element of the
    // queue
    static int kElement(Queue<Integer> q, int K)
    {
        // If the queue size is less than K, return -1
        if (q.size() < K)
            return -1;

        // Declare a TreeSet (sorted set) to store unique
        // elements
        TreeSet<Integer> set = new TreeSet<>();

        // Loop to insert every element of the queue into
        // the set
        while (!q.isEmpty()) {
            // Insert the current front element into the set
            set.add(q.peek());

            // Remove the current front element
            q.poll();
        }

        // Check if set size is less than K
        if (set.size() < K)
            return -1;

        // Initialize the index by 1
        int index = 1;

        // Loop to find the Kth largest element
        for (int element : set) {
            // If the sorted index is equal to K, return the
            // element
            if (index == (set.size() - K + 1))
                return element;

            // Increment the index by 1
            index++;
        }

        return -1;
    }

    // Driver Code
    public static void main(String[] args)
    {
        Queue<Integer> q = new LinkedList<>();

        // Pushing elements into the queue
        q.add(15);
        q.add(27);
        q.add(18);
        q.add(13);

        int K = 2;

        // Call the function and store the return value into
        // kMaxx
        int kMaxx = kElement(q, K);

        // Print the Kth largest element
        System.out.println(
            "The " + K + "th largest element is " + kMaxx);
    }
}

// This code is contributed by Susobhan Akhuli
Python3
# Python program to find the Kth largest element present
# in the queue

from queue import Queue

# Function which returns Kth largest element
# of the queue
def kElement(q, K):
    # If queue size is less than K
    # then return -1
    if q.qsize() < K:
        return -1

    # Declare SET st
    st = set()

    # Loop to insert every element of queue inside set
    while not q.empty():
        # inserting current front element inside set
        st.add(q.queue[0])

        # pop current front element
        q.get()

    # To store set size/length
    N = len(st)

    # Check if set size is less than K
    if N < K:
        return -1

    # Initialize index by 1
    ind = 1

    # Loop to find K'th largest element
    for it in sorted(st):
        # If sorted index is equal to k
        # return element of that index
        if ind == (N - K + 1):
            return it

        # Increment the index by 1
        ind += 1


# Driver Code
if __name__ == '__main__':
    q = Queue()

    # Pushing elements into queue
    q.put(15)
    q.put(27)
    q.put(18)
    q.put(13)

    K = 2

    # Call function and store return value into kMaxx
    kMaxx = kElement(q, K)

    # print the Kth largest element
    print("The ", K, "th largest element is ", kMaxx, sep='')

# This code is contributed by Susobhan Akhuli
C#
// C# program to find the Kth largest element
// present in the queue
using System;
using System.Collections.Generic;
using System.Linq;

class GFG {
    // Function which return Kth largest element
    // of the queue
    static int KElement(Queue<int> q, int K)
    {
        // If queue size is less than K
        // then return -1
        if (q.Count < K)
            return -1;

        // Declare SortedSet st
        SortedSet<int> st = new SortedSet<int>();

        // Loop to insert every element of queue
        // inside SortedSet
        while (q.Count > 0) {
            // Inserting current front element
            // inside SortedSet
            st.Add(q.Peek());

            // Dequeue current front element
            q.Dequeue();
        }

        // To store SortedSet size/length
        int N = st.Count;

        // Check if SortedSet size is less than K
        if (N < K)
            return -1;

        // Initialize index by 1
        int ind = 1;

        // Loop to find K'th largest element
        foreach(int item in st)
        {
            // If sorted index is equal to k
            // return element of that index
            if (ind == (N - K + 1))
                return item;

            // Increment the index by 1
            ind++;
        }

        return -1; // Default return statement (to satisfy
                   // the C# compiler)
    }

    // Driver Code
    static void Main()
    {
        Queue<int> q = new Queue<int>();

        // Pushing elements into queue
        q.Enqueue(15);
        q.Enqueue(27);
        q.Enqueue(18);
        q.Enqueue(13);

        int K = 2;

        // Call function and store return value
        // into kMaxx
        int kMaxx = KElement(q, K);

        // Print the Kth largest element
        Console.WriteLine(
            "The " + K + "th largest element is " + kMaxx);

        // Wait for user input to exit
        Console.ReadLine();
    }
}

// This code is contributed by Susobhan Akhuli
JavaScript
// Javascript program to find the Kth largest element
// present in the queue
function kElement(q, K) {
  // If queue size is less than K, return -1
  if (q.length < K) {
    return -1;
  }

  // Create a set to store unique elements
  const set = new Set();

  // Insert every element of the queue into the set
  while (q.length > 0) {
    set.add(q.shift());
  }

  // Get the size of the set
  const N = set.size;

  // If set size is less than K, return -1
  if (N < K) {
    return -1;
  }

  // Initialize index
  let ind = 1;

  // Iterate through the set to find the Kth largest element
  for (const value of set) {
    if (ind === N - K + 1) {
      return value;
    }
    ind++;
  }
}

// Driver code
  const q = [15, 27, 18, 13];
  const K = 2;

  // Call the function and store the return value
  const kMaxx = kElement(q, K);

  // Print the Kth largest element
  console.log(`The ${K}th largest element is ${kMaxx}`);



// This code is contributed by Susobhan Akhuli

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.


Explore