Top K Highest Scores in Descending Order
Heaps, Sorting & SearchAuto-graded · 17 test casesLast updated
Select the k greatest values from an unsorted integer list, duplicates included, returned from largest to smallest, ideally in O(n log k) time using a bounded min-heap.
Top K Highest Scores
You are given an unsorted list of integers scores and a positive integer k. Return the k greatest values in the list, ordered from largest to smallest.
Rules
- Duplicates count separately. If a value appears several times, each occurrence is a separate candidate. For example, if the two largest entries are both
5, the result contains5twice. - Do not remove duplicates from the input.
- The result must have exactly
kelements and be sorted in descending (non-increasing) order. - Negative numbers are ordinary values and are compared normally.
- If
kequals the length of the list, return the entire list sorted in descending order. - Do not modify the input in a way that affects the returned value; only the returned list is checked.
Sorting the entire list works, but a stronger answer avoids a full sort when k is much smaller than the list length by keeping only a bounded collection of the best candidates seen so far.
Constraints
1 <= k <= len(scores)1 <= len(scores) <= 10^6-10^9 <= scores[i] <= 10^9
Examples
Example 1
Input: top_k_scores([3, 2, 1, 5, 6, 4], 2)
Output: [6, 5]
Example 2
Input: top_k_scores([3, 2, 3, 1, 2, 4, 5, 5, 6], 4)
Output: [6, 5, 5, 4]
Hints
Hint 1
You only need to remember the k best values seen so far, not the whole array. Which structure lets you quickly find and discard the weakest of those k?
Hint 2
Keep a min-heap of size k. Its root is the smallest of your current top k, so a new value only matters if it is strictly larger than the root.
Hint 3
A heap's internal order is not sorted order. After scanning everything, sort the k remaining values in descending order before returning them.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Sorting everything costs O(n log n), but only k values are needed. Maintain a min-heap that contains the k largest values seen so far. Its root is the smallest of those k values, so it is the threshold a new value must exceed to qualify.
- Take the first k values and heapify them.
- For each remaining value
x, ifxis strictly greater than the root, replace the root withx(heapreplace). Otherwise ignore it. - At the end, sort the heap's contents in descending order and return them.
Why it is correct
Invariant: after processing the first i >= k values, the heap holds the k largest values (as a multiset) among those i values.
- At the start, the first k values are trivially the k largest of themselves.
- When a new value
xarrives: ifxis not larger than the root, at least k values already in the heap are at least as large asx, soxis not needed. Ifxis larger than the root, the root is no longer among the top k, so swapping it forxpreserves the invariant. - After all values are processed, the heap holds the overall k largest.
Duplicates are handled naturally because the heap stores a multiset; equal values are interchangeable, so using strict > loses nothing. The all-equal case and k == len(scores) work without special handling, and negatives need no special treatment since the heap compares values directly.
Complexity
- Time: O(k) to heapify, O((n - k) log k) for the scan, and O(k log k) for the final sort, giving O(n log k) overall.
- Space: O(k) beyond the input.
Reference solution
import heapq
from typing import List
def top_k_scores(scores: List[int], k: int) -> List[int]:
# Min-heap holding the k largest values seen so far.
heap = scores[:k]
heapq.heapify(heap)
for x in scores[k:]:
# Only a value that beats the current k-th largest can enter.
if x > heap[0]:
heapq.heapreplace(heap, x)
# Heap order is not sorted order, so sort descending for output.
return sorted(heap, reverse=True)