An interactive visualization of the min-heap approach. Watch how a min-heap of size k is maintained to efficiently find the kth largest element without fully sorting the array.
Heap / Priority Queue LeetCode 215 โ Mediumnums and an integer k, return the
kth largest element in the array.k elements. At the end, the heap's minimum (the root) is the kth largest element.
import java.util.PriorityQueuefun findKthLargest(nums: IntArray, k: Int): Int { val heap = PriorityQueue<Int>() for (num in nums) { heap.add(num) if (heap.size > k) { heap.poll() } } return heap.peek()!!}
Instead of sorting the entire array, we maintain a min-heap of size k. As we iterate through the array, the heap always holds the k largest elements seen so far. The smallest of those k elements sits at the top of the min-heap. When we finish processing all elements, that heap root is exactly the kth largest element in the array.
A min-heap lets us efficiently access and remove the smallest element. By capping the heap at size k, we ensure that anything smaller than the current kth largest gets evicted. After processing all elements, only the k largest remain, and the root (minimum of those k) is our answer.
heap[0]: The root of the min-heap is the kth largest element
We iterate through all n elements, and each heap push/pop operation takes O(log k) time
since the heap never exceeds size k. This is better than sorting (O(n log n)) when k is much smaller than n.
The space complexity is O(k) for the heap storage.