Top-K Cutoff: Find the K-th Highest Value
Heaps, Sorting & SearchAuto-graded · 20 test casesLast updated
Tests order-statistics intuition by asking candidates to extract the k-th largest element from an unsorted array without a full sort.
Problem
You are given an unsorted list of integers and a positive integer k. Your task is to return the k-th highest value in the list.
Think of it this way: if you lined up all the values from largest to smallest (keeping every duplicate in its own position), the answer is the value sitting at position k in that line.
For example, with the list [5, 5, 4] and k = 2, position 1 holds 5, and position 2 also holds 5 — so the answer is 5, not 4. Duplicates occupy separate positions.
Input:
nums: an unsorted list of integers (may contain duplicates)k: a positive integer, guaranteed to satisfy1 <= k <= len(nums)
Output:
- A single integer — the value that would appear at index
k - 1in the list sorted in descending order.
Constraints
1 <= len(nums) <= 2 * 10^5-10^9 <= nums[i] <= 10^91 <= k <= len(nums)- Duplicates count as distinct positions in the ranking.
- You may not assume the input is sorted or free of repeated values.
- Aim for a solution better than
O(n log n)time.
Examples
Example 1
Input: kth_largest([3, 2, 1, 5, 6, 4], 2)
Output: 5
Example 2
Input: kth_largest([5, 5, 4], 2)
Output: 5
Hints
Hint 1
Sorting the whole array gives a correct but suboptimal O(n log n) answer — can you avoid sorting elements that can never be in the top k?
Hint 2
Think about what data structure lets you cheaply track the k largest values seen so far and immediately discard a value the moment you know it can't make the cut.
Hint 3
A min-heap of exactly k elements is the key. Its root is always the weakest member of your current top-k shortlist — use that root as a gatekeeper when scanning the rest of the array.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why not just sort?
Sorting in descending order and returning index k - 1 is correct and simple (O(n log n)), but it does unnecessary work — we rank every element when we only care about the top k.
The min-heap shortlist
The core idea: maintain a shortlist of exactly k elements representing the largest values encountered so far. We need to quickly identify and evict the weakest member of that shortlist whenever a stronger candidate arrives. A min-heap is perfect for this, because it exposes the minimum (the weakest member) at the root in O(1).
Algorithm:
- Copy the first
kelements into a list and callheapifyto build a min-heap inO(k). - Scan every remaining element
vone by one:- If
v > heap[0], thenvis stronger than the current weakest member of the shortlist. Evict that weakest member and admitvusingheapreplace(a singleO(log k)operation). - Otherwise
vcannot be in the topk, so skip it.
- If
- After the full scan, the heap holds exactly the
klargest values. Its minimum,heap[0], is the k-th largest value in the entire list.
Why a min-heap for a "largest" problem?
We are not looking for the largest overall — we already have k candidates. We want to cheaply ask: "Is this newcomer better than the worst member of my shortlist?" The min-heap puts the worst member (the minimum of the shortlist) at the root, giving us that comparison in O(1) and replacement in O(log k).
Correctness
Invariant: after processing the first i elements (i >= k), the heap contains the multiset of the k largest values among those i elements, with duplicates counted individually.
- Base case: after seeding with the first
kelements, the invariant holds trivially. - Inductive step: for a new value
v:v > heap[0]:vdisplaces the current weakest member. The new top-k is the old top-k minus its minimum, plusv.heapreplacedoes exactly this.v <= heap[0]:vis no better than the current weakest member, so the top-k multiset is unchanged. Skipping is correct.
- Duplicates: the heap stores every occurrence as a separate entry. For
[5, 5, 4]withk = 2, the heap is seeded with[5, 5], then4fails the> heap[0]check and is skipped. The answer isheap[0] = 5. ✓
Complexity
| Time | O(n log k) — O(k) to build the initial heap, then at most n - k calls to heapreplace each costing O(log k) |
| Space | O(k) — the heap never grows beyond k elements |
When k is small relative to n, this is close to linear. Even at k = n it is no worse than O(n log n).
Alternative: Quickselect
Quickselect partitions around a pivot and recurses only into the side containing the target rank, achieving O(n) average time and O(1) extra space. The tradeoff: it mutates the input, has O(n²) worst-case behavior without randomization, and requires a three-way (Dutch national flag) partition to handle duplicates without degrading. The heap approach is deterministically O(n log k), leaves the input untouched, and also works on a data stream — making it the more practical choice in most settings.
Reference solution
import heapq
from typing import List
def kth_largest(nums: List[int], k: int) -> int:
# Seed the heap with the first k elements (copy so the caller's list is untouched).
heap = nums[:k]
heapq.heapify(heap) # O(k) — turns the list into a valid min-heap in place
for value in nums[k:]:
# The heap root is the smallest of the k largest values seen so far.
# Only values that beat it can possibly belong in the top k.
if value > heap[0]:
heapq.heapreplace(heap, value) # atomic pop-min + push, O(log k)
# After scanning all elements, heap[0] is the smallest of the k largest,
# which is exactly the k-th largest overall.
return heap[0]