Kth Largest Element in an Array
Medium · Heap & Counting · Array · Heap · Quickselect · Sorting
Problem
Return the k-th largest value in nums, counting by position in sorted order rather than by distinct value — so in [3,3,1] the 2nd largest is 3.
Examples
Input: nums = [3,2,1,5,6,4], k = 2 Output: 5
Sorted descending: 6, 5, 4…
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 Output: 4
Duplicates each take a position.
Constraints
- 1 <= k <= len(nums) <= 10^5
- -10^4 <= nums[i] <= 10^4
Approaches
- Sort and index — time O(n log n), space O(n)
Related problems
Start free on Cariara · Coding problems · System design studio