Challenge
Return the k distinct values with highest frequency. Output must be ordered by frequency descending, then numeric value ascending. A tie at the cut-off must follow the same rule.
Input and output contract
0 ≤ n ≤ 60,000; at most 5,000 distinct integers; |value| ≤ 1,000,000; 0 ≤ k ≤ distinct count. k=0 returns [].
All tests follow this contract. You do not need to validate malformed input. Return the requested result from top_k_frequent; printed output is not your answer. Standard-library tools are allowed. Implement your solution in Python 3.12.
Target complexity: O(n + u log(k + 1) + k log(k + 1)) expected time; O(u + k) space
Return values are checked by type. Use the exact function name. Print output is not your answer. Tests have time and memory limits.
Public examples
Arguments
[[4, 4, 1, 1, 2, 2, 3], 2]
Expected return
[1, 2]
Arguments
[[9, 9, 2, 2, 2], 1]
Expected return
[2]
Arguments
[[5], 0]
Expected return
[]
Hint
Count first. In a size-k min-heap, the least desirable retained item has the smallest (frequency, -value).
The worked solution unlocks after completion, or with Premium access.