Priority Queue Kth Largest
Given an array of integers and an integer k, find the kth largest element in the array. The kth largest is the element that would appear at position k-1 (0-indexed) if the array were sorted in descending order. Return the element itself. If k exceeds the array length, return -1.
For example, in the array [3, 2, 1, 5, 6, 4] with k=2, the sorted descending order is [6, 5, 4, 3, 2, 1], and the 2nd largest is 5. With k=1, the result is 6 (the maximum). With k=6, the result is 1 (the minimum). With k=7, which exceeds the array length, return -1.
The kth largest element is a classic selection problem with applications in statistics (percentiles), leaderboards (top performers), and ranking systems. It is the mirror image of the kth smallest problem and shares the same algorithmic approaches.
The simplest approach sorts the array in descending order and returns the element at index k-1. This runs in O(n log n) time. A more efficient approach for large arrays uses a min-heap (priority queue) of size k: maintain only the k largest elements seen, and the top of the heap (the smallest among them) is the kth largest.
Edge cases include k=1 (return the maximum element), k equal to the array length (return the minimum element), k larger than the array length (return -1), and an empty array (return -1).
Example Input & Output
Not enough elements
1st largest is max
2nd largest is 4
Single
3rd largest is min
Algorithm Flow
Solution Approach
Maintain a min-heap of size k to track the k largest elements. For each element, push it into the heap. If the heap exceeds size k, pop the smallest element (the heap's top). After processing all elements, the heap contains the k largest values, and its top is the kth largest.
The heap only retains the k largest values, discarding smaller ones. The top element is the kth largest after the full pass.
Time O(n log k), Space O(k).
Best Answers
import java.util.*;
class Solution {
public int solution(int[] nums, int k) {
if(k>nums.length)return -1;int[] s=nums.clone();Arrays.sort(s);return s[s.length-k];
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
