← Back to DSA
#215
Kth Largest Element in an Array
Kth Largest Element in an Array solution for LeetCode 215, with the key idea, complexity breakdown, and working code in Java, C++, JavaScript, TypeScript, C, Go, and Rust.
Solve on LeetCode ↗Kth Largest Element in an Array
Why it belongs on this sheet
This problem is the reusable heap version of top-k selection and shows up constantly in interview prep.
Pattern
Min-heap of size k
Approach
Maintain a min-heap containing the largest k elements seen so far. Once the scan ends, the heap top is the kth largest.
Java solution
import java.util.PriorityQueue;
class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> heap = new PriorityQueue<>();
for (int num : nums) {
heap.offer(num);
if (heap.size() > k) {
heap.poll();
}
}
return heap.peek();
}
}
Complexity
- Time:
O(n log k) - Space:
O(k)
Interview note
Quickselect is a good follow-up, but the heap answer is usually the safest first explanation.
Dynamic Programming
7 DP Patterns > 100 LeetCode Questions
Most DP questions are repeated ideas. Stop treating DP like chaos. Learn the 7 repeatable patterns that unlock most placement-level questions.
7 patternsProgress tracking
Read 7 patterns (5 min)