Example 1
ready- Input
nums = [ 3, 2, 1, 5, 6, 4 ] k = 2- Expected
5- Why
- descending order starts 6, 5, so rank 2 is 5
A tournament has 100,000 scores, but the podium question is narrow: which score sits
in position k when the leaderboard runs from highest to lowest?
Given an integer array nums and an integer k, return the k-th largest value.
k uses 1-based ranking, so k = 1 asks for the maximum and k = nums.length asks
for the minimum.
A few ground rules:
[9, 9, 4], both the
first- and second-largest values are 9.1 <= k <= nums.length <= 100_000-10_000 <= nums[i] <= 10_000Hints
Sort a copy from largest to smallest and read position k - 1. It works. Now ask
how much of that sorted order you actually use.
A min-heap is a structure that exposes its smallest stored value first. If it
holds the k largest values seen so far, its smallest value is exactly the current
k-th largest.
Grow the heap to size k. After that, replace its root only when a new value is
larger. Values at or below the root can't enter the final top k.
Can you find the answer in average O(n) time by partitioning the array instead of maintaining a heap?
Visible cases
nums = [
3,
2,
1,
5,
6,
4
]
k = 25nums = [
3,
2,
3,
1,
2,
4,
5,
5,
6
]
k = 44nums = [
-5,
-2,
-9,
-2
]
k = 3-5Interview signal
The direct route builds the entire leaderboard. Sort a copy in descending order, then
read index k - 1.
def find_kth_largest(nums: list[int], k: int) -> int:
ranked = sorted(nums, reverse=True)
return ranked[k - 1]Duplicates need no special handling. Sorting keeps both copies, so each one consumes a rank exactly as the statement requires.
Time O(n log n), space O(n) for the sorted copy.
You never need the full ranking. Keep only the best k values seen so far in a
min-heap, a structure whose root is its smallest value.
Once the heap contains k values, that root is the cutoff for the current top k:
k.k, so insert it and evict the old root.import heapq
def find_kth_largest(nums: list[int], k: int) -> int:
contenders: list[int] = []
for score in nums:
heapq.heappush(contenders, score)
if len(contenders) > k:
heapq.heappop(contenders)
return contenders[0]After every score, the heap holds the k largest values from the prefix you've read.
At the end that prefix is the whole array, and the smallest of those contenders is the
answer.
Time O(n log k), space O(k) for a heap that never grows beyond k + 1 entries.
Ready to run.
3 cases are queued.
Visible testcase
Case 1
Expected
5