Pick the Element at a Given Rank From the Top
Heaps, Sorting & SearchAuto-graded · 19 test casesLast updated
Find the k-th largest value in an unsorted integer list, counting duplicates separately, without necessarily sorting the whole list.
You are given an unsorted list of integers values and a positive integer rank. Return the value that would sit at position rank if the list were ordered from largest to smallest, where position 1 is the largest.
Equal values are counted as separate entries. For example, in [3, 3, 2] the 1st largest is 3, the 2nd largest is 3, and the 3rd largest is 2.
A full sort is a valid baseline, but try to do better: a bounded-size heap or a partition-based selection avoids ordering the entire list.
Your function should not depend on the input being sorted, and it may be given negative numbers and repeated values.
Constraints
1 <= rank <= len(values)valuescontains at least one integer- Each value is a (possibly negative) integer that fits in a standard 32-bit signed range
- The returned value is a single integer taken from
values
Examples
Example 1
Input: kth_from_top([3, 2, 1, 5, 6, 4], 2)
Output: 5
Example 2
Input: kth_from_top([3, 2, 3, 1, 2, 4, 5, 5, 6], 4)
Output: 4
Example 3
Input: kth_from_top([7], 1)
Output: 7
Hints
Hint 1
Think about what the answer would be if the list were sorted in descending order. Which index would you read?
Hint 2
You only need to track the `rank` largest values seen so far. Which heap type lets you cheaply discard the smallest of those?
Hint 3
Keep a min-heap of size `rank`. For each remaining number, if it beats the heap's root, replace the root. After one pass, the root is the answer. Quickselect is an alternative with O(n) expected time.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Maintain a min-heap that holds the rank largest values seen so far.
- Put the first
rankvalues into a list and turn it into a min-heap. The root is the smallest of these. - For each remaining value, compare it with the root. If it is larger, the root cannot be among the
ranklargest anymore, so replace the root with the new value (heapreplacepops and pushes in one step). Otherwise ignore it. - After the pass, the heap holds exactly the
ranklargest values, and its root is the smallest of them, which is therank-th largest overall.
Why it is correct
At every step the heap contains the rank largest elements of the prefix processed so far. A new value only enters if it is strictly greater than the smallest member, which evicts that member, and the invariant is preserved. Duplicates are handled naturally because each occurrence is a separate entry in the heap. When the pass ends, the root is the smallest among the top rank entries, which is by definition the rank-th largest.
Complexity
- Time: O(n log k), where
k = rank. Building the initial heap is O(k), and each of the remaining n - k elements costs at most O(log k). - Space: O(k) for the heap.
An alternative is quickselect with a three-way partition, which gives O(n) expected time and handles duplicates well, but the heap version is simpler and also works on streaming input.
Reference solution
import heapq
from typing import List
def kth_from_top(values: List[int], rank: int) -> int:
heap = values[:rank]
heapq.heapify(heap)
for v in values[rank:]:
if v > heap[0]:
heapq.heapreplace(heap, v)
return heap[0]