VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-kth-largest-smallest-element-in-a-queue/

⇱ Find Kth Largest/Smallest element in a Queue - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find Kth Largest/Smallest element in a Queue

Last Updated : 23 Jul, 2025

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:


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.

Comment
Article Tags: