![]() |
VOOZH | about |
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:
Below is the implementation of the above approach to find K'th largest:
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.