Kth Largest Element in an Array
Given an integer array nums and an integer k, return the k-th largest element in the array.
Note that it is the k-th largest element in the sorted order, not the k-th distinct element.
Examples
nums = [3,2,1,5,6,4], k = 25nums = [3,2,3,1,2,4,5,5,6], k = 44Constraints
1 <= k <= nums.length <= 10^5-10^4 <= nums[i] <= 10^4
š” Hints
Hint 1
Maintain a min-heap of size k as you iterate through the array.
Hint 2
If the heap size exceeds k, pop the minimum element.
Hint 3
After iterating through all elements, the top of the min-heap is the kth largest element.
Algorithm Complexity
Official asymptotic Big-O runtime and auxiliary memory analysis
Use a Min-Heap of capacity k. Insert each element into the heap. When the heap size exceeds k, remove the smallest element. The remaining top element is the kth largest.
Maintaining a min-heap of size K requires O(log K) insertion/extraction for each of the N elements.
The min-heap stores at most K elements at any point.
š Real-World Use Cases
Streaming billions of tweets and maintaining top K hashtags using a bounded min-heap.
š Dry Run
Iterate num = 3 and num = 2. Push into min-heap. Size = 2 (matches k = 2).