Example 1
- Input
- nums = [3,2,1,5,6,4], k = 2
- Output
- 5
Sorted, the array is [1,2,3,4,5,6], and the element two places from the end is 5.
Given an unsorted array and an integer k, return the kth largest element in sorted order while counting duplicates separately. For example, the 2nd largest of [3,2,1,5,6,4] is 5.
Given an integer array nums and an integer k, return the kth largest element in the array.
Ranking follows the sorted order and not the distinct order, so duplicates count as separate positions: in [3,2,3,1,2,4,5,5,6] the 4th largest is 4.
1 <= k <= nums.length <= 10^5-10^4 <= nums[i] <= 10^4Sorted, the array is [1,2,3,4,5,6], and the element two places from the end is 5.
Sorted, the array is [1,2,2,3,3,4,5,5,6], and the element four places from the end is 4.
With one occurrence, the largest and smallest ranks coincide. The only valid k is 1, so the negative boundary value itself is the answer; zero would be an incorrect default.
The kth largest is a rank among occurrences, so equal values occupy separate places. Sorting reveals every rank; a min-heap retains only the k largest occurrences with their smallest at the root. Quickselect instead partitions around a pivot, placing smaller, equal and larger values in separate regions, then searches only the region containing ascending index n - k. For Example 1 that index is 4; partitioning around 4 and then 5 locates the answer 5 without sorting every value. The heap preserves nums and guarantees its time bound; randomized Quickselect rearranges nums and has a faster expected bound but a quadratic worst case.
Reveal Sort Once: intuition, complexity, and code
length - k, so double-check that arithmetic on Example 1.k survivors matter, which suggests discarding small values as soon as a k + 1th candidate appears.k entries keeps the smallest survivor on top, and that top is the answer.n - k.k = 1, which asks for the plain maximum of the array.k equal to the array length, which asks for the plain minimum.-10000, where k = 1 returns that element without a default zero.k or length - k - 1 after sorting instead of length - k.4, but the answer is 5.(a, b) => a - b.Ranking does not require fully sorting: a size-k min-heap tracks a cutoff in a stream, while randomized three-way Quickselect repeatedly discards regions that cannot contain the target rank. Choose the heap for preserved input and a guaranteed bound; choose in-place selection for expected linear work on a fixed array.