Kth Largest Element in an Array
Medium ArrayDivide and ConquerSortingHeap (Priority Queue)Quickselect
Key Insight:You don't need to fully sort the array—maintaining just the k largest elements in a min-heap lets you efficiently track the kth largest as the heap's minimum, discarding smaller elements as you go.
Approaches
Insight Challenge
Why do we use a min-heap of size k instead of a max-heap?
Maintain only the top k candidates as we scan
Instead of sorting everything, we can maintain a collection of the k largest elements seen so far. The smallest element in this collection is our answer—if a new element is smaller than our current kth largest, it can't possibly be in the top k. A min-heap naturally surfaces the smallest element for efficient comparison and replacement.
Algorithm
- Create an empty collection to hold candidates
- Process each element in the array:
- Add the element to our candidate collection
- If we have more than k candidates, remove the smallest
- The smallest remaining candidate is the kth largest overall
Solution
Time O(n log k) Space O(k)
def find_kth_largest(nums, k):
import heapq
min_heap = []
for num in nums:
heapq.heappush(min_heap, num)
if len(min_heap) > k:
heapq.heappop(min_heap)
return min_heap[0]