Statementâ–¼
Find the kth largest element in an unsorted array.
Note: We need to find the kth largest element in the sorted order, not the kth distinct element.
Constraints:
-
1≤
k
≤nums.length
≤103 -
−104≤
nums[i]
≤104
Solution
The intuition behind using a min-heap is efficiently managing a subset of elements for the kth​ largest position as the array is processed. Initially, the heap is filled with the first k elements of the array, setting up an initial set of elements. As we iterate through the remaining elements, the algorithm evaluates each against the current smallest element (the root of the heap). If an element is larger, the top is removed, and the larger element is added to the heap, ensuring that the heap always contains the k largest elements seen so far. Consequently, once all elements are processed, the root of the min-heap represents the kth largest element.
The slides below illustrate the core idea of our algorithm: