← DiffPush

Kth Largest Element in an Array

Baseline Heaps · Medium Problems O(n log k) · O(k)

The Leaderboard Podium Scan

An esports backend tracks player scores in arrival order, and the broadcast needs the kth-highest score without sorting the entire leaderboard. A small holding pen keeps only the k best scores seen so far, always evicting its weakest resident whenever a stronger score arrives. When the scan ends, the pen's weakest resident is exactly the kth-highest score overall.

Input: An integer array nums and an integer k.

Output: Return the kth largest element of nums.

Constraints

Examples

Example 1

Input: {"nums":[3,2,1,5,6,4],"k":2}
Output: 5
Only 6 outranks 5, so 5 is the second-highest score.

Example 2

Input: {"nums":[3,2,3,1,2,4,5,5,6],"k":4}
Output: 4
The scores above 4 are 6, 5, 5 — making 4 the fourth-largest.

Solve this in your browser →

Also on LeetCode ↗