Return the distinct input values that occur most frequently, rather than the largest numeric values.
Problem
Input. An integer list nums and integer k with 0 <= k <= u, where u is its distinct-value count.
Output. Return k distinct values with the highest occurrence counts.
Rules. Rank by frequency, not by numeric value. Equal occurrences contribute to their value’s count.
Any selection among cutoff-tied values is valid, and no output ordering is required.
Leave the input unchanged. Rank zero returns []; an empty list therefore permits only zero.
Example. [1, 1, 1, 2, 2, 3] with k = 2 returns [1, 2] in either order.
For [5, 5, 9] and k = 1, return [5], not [9].
Picture
Imagine a row of coordinates labelled 0 through n.
A value’s frequency tells you exactly where it belongs.
No positive count exceeds the input length n.
| Value | Frequency | Bucket |
|---|---|---|
1 | 3 | 3 |
2 | 2 | 2 |
3 | 1 | 1 |
Skip empty buckets 6,5,4, take value 1 from bucket 3, then value 2 from bucket 2.
Problem trace
Separate count buckets: frequency, not numeric value, determines order
Reference drawing
Problem trace
Frequency chooses the bucket; each distinct value enters that bucket once
Execution trace
- key 1
- 3
- key 2
- 2
- key 3
- 1
- key 1
- 3→not shown
- key 2
- 2→not shown
- key 3
- 1→not shown
- scan f
- 6→3
- skipped
- not shown→f=6,5,4
- direction
- 6 -> 0→not shown
- answer
- []→[1]
- check
- not shown→1 < 2; continue
- skipped
- f=6,5,4→not shown
- take [2]
- 3→2
- answer
- [1]→[1,2]
- check
- 1 < 2; continue→2 >= k
- Recognize it
- Use frequency buckets when the answer ranks values by occurrence count, counts cannot exceed the input length n, and linear time matters more than ordering values within equal-frequency buckets.
- Keep true
- Before scanning bucket f, the answer contains every value from frequencies greater than f and no value from a lower frequency. Therefore the first k collected values are among the k most frequent.
- Reuse it
- Whenever a ranking key is a small bounded integer, use that key as an array coordinate and scan coordinates in answer order; this transfers to counting sort, histogram selection, and bounded-score ranking.
Before scanning bucket f, all higher-frequency candidates have been collected; no lower-frequency candidate has been collected.
That ordering makes the first k collected values a valid selection.
A cutoff bucket can temporarily add more than k; slicing keeps exactly k.
Code
from collections import Counter
def top_k_frequent(nums: list[int], k: int) -> list[int]:
frequencies = Counter(nums)
buckets: list[list[int]] = [[] for _ in range(len(nums) + 1)]
for num, frequency in frequencies.items():
buckets[frequency].append(num)
answer: list[int] = []
for bucket in reversed(buckets):
answer.extend(bucket)
if len(answer) >= k:
return answer[:k]
return answer
Expected time and storage are , including counts, n+1 buckets, and collected values.
Hashing supports the expected-time qualification.
The input is unchanged.
Failure Check
Do not replace frequency priority with numeric rank.
Within a bucket, this Python reference follows first appearance, not numeric order.
For [2,1,3,3], k=2 returns [3,2]; [3,1] is also a valid tied selection.
k=0 returns [].
Larger k is outside the teaching contract; the literal source returns all candidates rather than raising.
Change the Coordinate Storage
New task: Avoid allocating n+1 buckets.
Picture and change: Keep exact counts, then select across the u distinct candidates with standard heap selection.
Retain Counter from the reference above.
import heapq
def top_k_by_heap(nums, k):
frequencies = Counter(nums)
return heapq.nlargest(k, frequencies, key=frequencies.get)
Check: The source returns [1,2]; k=0 returns [].
Expected work is , with state.
The exact count map remains: this is not an -memory heavy-hitter estimator.
Use when: The bucket range is costly relative to the distinct candidates and requested selection.
Change the Tie Contract
New task: Equal frequencies must prefer the smaller numeric value.
Picture and change: Order distinct values by (-frequency, value).
The extra key supplies an exact output order instead of an arbitrary cutoff choice.
def top_k_deterministic(nums, k):
frequencies = Counter(nums)
return sorted(frequencies, key=lambda value: (-frequencies[value], value))[:k]
Check: [2,1,3,3], k=2, now returns [3,1].
Expected counting plus comparison ranking costs time and storage.
Do not keep the bucket method’s linear ranking claim for this version.
Use when: Exact numeric tie order is part of the result contract.
Transfer Check
Why not apply the same direct bucket scan to arbitrary real-valued scores?
Answer
The small integer coordinate range justified the array allocation and scan. Continuous or unbounded scores need another ordering structure, or an explicitly lossy quantization rule. Compare bounded value heaps when the weakest retained candidate should be exposed directly.