Top frequent values
Return up to k distinct integers ordered by decreasing frequency, breaking ties by increasing value. k is nonnegative.
from collections import Counter
counts = Counter([3, 3, 2, 2, 1])
print(sorted(counts, key=lambda x: (-counts[x], x)))Reason about the state
Count frequencies first, then sort distinct keys with a compound ordering. Separating the tie rule makes the result deterministic. Before writing code, identify what each variable means after one iteration. Walk through the example and explain why the next transition preserves that meaning. Then check the smallest permitted input and a case with repeated values. A correct answer follows the contract for every input, including the boundary cases in the checks. Keep any input mutation within the stated rules; return a fresh result when the task asks for one.
Your task
Return up to k distinct integers ordered by decreasing frequency, breaking ties by increasing value. k is nonnegative.
The explanation opens here once every check passes.