Solution: Kth Largest Element in an Array
Let's solve the Kth Largest Element in an Array problem using the Top K Elements pattern.
We'll cover the following
Statement
Find the largest element in an unsorted array.
Note: We need to find the largest element in the sorted order, not the distinct element.
Constraints:
-
k
nums.length
-
nums[i]
Solution
The intuition behind using a min-heap is efficiently managing a subset of elements for the ​ largest position as the array is processed. Initially, the heap is filled with the first 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 largest elements seen so far. Consequently, once all elements are processed, the root of the min-heap represents the largest element.
The slides below illustrate the core idea of our algorithm: