AceYourInterviews
Checking sign-in…

69. Kth Largest Element in an Array

IntermediateSize-k min-heap selection

Imagine sorting all input occurrences from largest to smallest. Return the value at rank k, where k equals one means the maximum.

This is not the kth distinct value. Repeated occurrences each occupy a rank, and the original array must follow the documented mutation rules.

Example 1

Input

nums=[3,2,1,5,6,4], k=2

Output

5

Explanation: Only 6 is strictly greater than 5.

Example 2

Input

nums=[5,5,4], k=2

Output

5

Explanation: Duplicate occurrences occupy separate ranks.

Constraints

  • 1 <= nums.length <= 105
  • -231 <= nums[i] <= 231 - 1
  • 1 <= k <= nums.length
Hints
Hint 1

What information can be discarded when only k large occurrences matter?

Hint 2

Make the least valuable retained candidate easy to remove.

Hint 3

Maintain a min-heap of at most k occurrences; return its root.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Retain only the top two

[3,1,5,2,4]
2
4