9.1 Find k-th Largest Element in an Array
9.1.1 Problem Metadata
- Platform: LeetCode
- Problem ID: 215
- Difficulty: Medium
- URL: https://leetcode.com/problems/lc-kth-largest-element-in-an-array/
- Tags: Blind 75, NeetCode 150
- Techniques: Heap, Array, Divide and Conquer
9.1.2 Description
Given an unsorted array nums and an integer k, return the k-th largest element in the array. The k-th largest element is the element that would appear at index n - k after sorting the array in ascending order.
9.1.3 Examples
Input: nums = [3,2,1,5,6,4], k = 2
Output: 5
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4
9.1.5 Solution - Size-k Min Heap
9.1.5.1 Walkthrough
Maintain a min heap that keeps track of the current k largest elements seen so far. Iterate over nums, pushing each number into the heap and immediately popping whenever the heap size exceeds k. After processing all numbers, the heap root is the k-th largest element because every larger value is still inside the heap.
9.1.5.2 Analysis
- Time Complexity: O(n log k) because each insertion and possible removal costs
log k - Space Complexity: O(k) for the heap