← Programming questions
Medium / PYTHON

Top K Frequent Values with Tie-Breaking

hash_maps · heaps · sorting 25 minute study target

Not completed

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

Example 1

Arguments

[[4, 4, 1, 1, 2, 2, 3], 2]

Expected return

[1, 2]
Example 2

Arguments

[[9, 9, 2, 2, 2], 1]

Expected return

[2]
Example 3

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.

top_k_frequent.pyPython 3.12

Drafts are saved to your account, not to shared browser storage.

Sign in to submit code and save progress.

Results

Your results will appear here.

Hidden tests reveal only their pass/fail status, never their inputs or expected outputs. Runtime is observed wall time—not an inferred complexity class.

© 2026 EverythingQuant. All Rights Reserved.