Kth Largest Element in an Array
mediumNeetCode 150heapquickselectarrays
Problem
Given a list of integers and a number k, return the kth largest element in sorted order, where duplicates count as distinct positions. Aim for better than a full sort.
Examples
Input: nums = [3, 2, 1, 5, 6, 4], k = 2
Output: 5
The second largest value is 5.
Input: nums = [3, 2, 3, 1, 2, 4, 5, 5, 6], k = 4
Output: 4
Fourth largest counting duplicates.
Constraints
- • 1 <= k <= nums.length <= 10^5
- • -10^4 <= nums[i] <= 10^4
Hints(tap to reveal)
- 1. A size-k min-heap keeps the largest k seen.
- 2. Quickselect averages linear time.
Optimal approach(spoiler)
- Maintain a min-heap of size k while scanning the array.
- Push each value; if the heap exceeds k, pop the smallest.
- After the scan the heap root is the kth largest.
- Quickselect partitioning is an O(n) average alternative.
- Heap approach is O(n log k) time, O(k) space.
Ready to solve it?
Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.
Practice in the editor