Pick the Rank-k Score From the Top
Heaps, Sorting & SearchAuto-graded · 21 test casesLast updated
Select the k-th largest value, counting duplicates separately, from an unsorted integer list without a full sort, using quickselect or a bounded heap.
Pick the Rank-k Score From the Top
You are given a list of integers scores (unsorted) and an integer k. Return the value that would be in position k if the scores were arranged from largest to smallest, where position 1 is the largest.
Rules
- Duplicates count separately. In
[5, 5, 4], the 1st largest is5, the 2nd largest is5, and the 3rd largest is4. You are not looking for the k-th distinct value. - Equivalently, the answer is the element at index
len(scores) - kof the list sorted in ascending order. - Do not modify the caller's list.
- Aim to avoid sorting the entire list. A randomized partition-based selection (expected linear time) or a min-heap capped at size
k(O(n log k) time) are the usual approaches. Only the returned value is checked.
Input
scores: a list ofnintegers (may include negative values and repeated values).k: an integer with1 <= k <= n.
Output
- A single integer: the k-th largest value in
scores.
Constraints
1 <= k <= n = len(scores)- Values are integers and may be negative or repeated.
k = 1yields the maximum andk = nyields the minimum.- A single-element list returns that element.
Examples
Example 1
Input: kth_largest_score([3, 2, 1, 5, 6, 4], 2)
Output: 5
Example 2
Input: kth_largest_score([3, 2, 3, 1, 2, 4, 5, 5, 6], 4)
Output: 4
Example 3
Input: kth_largest_score([-1, -1], 1)
Output: -1
Hints
Hint 1
Sort order tells you where the answer lives: the k-th largest sits at ascending index n - k. You only need the one element that belongs at that index, not the entire sorted order.
Hint 2
Quickselect: partition around a random pivot, then continue only into the side that contains the target index. A three-way split (less, equal, greater) handles many duplicates cleanly, and if the target index falls in the equal block you are done.
Hint 3
Heap alternative: keep a min-heap holding the k largest values seen so far. When it grows past k, drop the smallest. After one pass, the root of the heap is the k-th largest.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The k-th largest value is the one that would sit at ascending index target = n - k in sorted order. We only need that single element, so a full sort is unnecessary.
Randomized three-way quickselect:
- Copy the input so the caller's list is untouched, and compute
target = n - k. - Maintain a window
[left, right]that is guaranteed to containtarget. - Choose a random pivot value from the window and partition the window into three consecutive blocks: values less than the pivot, values equal to it, and values greater than it. Let the equal block occupy indices
[lt, gt]. - If
target < lt, continue in the lower block (right = lt - 1). Iftarget > gt, continue in the upper block (left = gt + 1). Otherwisetargetlies in the equal block, so the answer is the pivot value.
While partitioning, when an element greater than the pivot is swapped to the right end, the index i is not advanced, because the element swapped in has not been examined yet.
Why it is correct
After the partition, everything left of the equal block is smaller than the pivot and everything right of it is larger. The equal block therefore occupies exactly the positions those values would have in sorted order. If target is in that block, its value is the pivot. Otherwise the element at target in sorted order must come from the one side that contains target, and the invariant "target is inside the window" is preserved. Since the pivot is taken from the window, the equal block is non-empty and the window strictly shrinks each round, so the loop terminates. Handling equal values as a block means duplicates are counted individually, as the problem requires, and an all-equal list finishes in one pass.
Complexity
- Time: expected O(n). A random pivot lands in the middle half with probability 1/2, shrinking the window to at most 3/4, giving a geometric series. The worst case is O(n^2) but is extremely unlikely.
- Space: O(n) for the defensive copy, O(1) auxiliary since the loop is iterative.
Alternative
A min-heap of size k (push each value, pop the minimum when the size exceeds k) leaves the k-th largest at the root. This takes O(n log k) time and O(k) space, and extends naturally to streaming input.
Reference solution
import random
from typing import List
def kth_largest_score(scores: List[int], k: int) -> int:
# Select the element at ascending index n-k using randomized 3-way quickselect.
arr = scores[:]
target = len(arr) - k
rng = random.Random(0)
left, right = 0, len(arr) - 1
while left <= right:
pivot = arr[rng.randrange(left, right + 1)]
lt, i, gt = left, left, right
while i <= gt:
if arr[i] < pivot:
arr[lt], arr[i] = arr[i], arr[lt]
lt += 1
i += 1
elif arr[i] > pivot:
arr[i], arr[gt] = arr[gt], arr[i]
gt -= 1
else:
i += 1
if target < lt:
right = lt - 1
elif target > gt:
left = gt + 1
else:
return arr[target]