Top-K Frequent Elements
Count, then rank — the two-step pattern behind trending topics, hot keys, and a thousand interview questions. A hash map does the counting; the ranking is where heaps, buckets, or a simple sort earn their keep.
The problem
Given nums, a list of integers, and k, return the k most frequent values, ordered by frequency descending; break frequency ties by the smaller value first. You may assume k ≤ the number of distinct values.
nums = [1,1,1,2,2,3], k = 2[1, 2]nums = [4,4,5,5,6], k = 2[4, 5]nums = [7], k = 1[7]- Order: frequency descending, then value ascending on ties.
- k ≤ number of distinct values in nums.
- Aim for O(n log n) or better (bucket sort by count gets O(n)).
Your turn — write it
Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are right above and Reveal solution is one click away.
Implement top_k_frequent(nums, k) → the k most frequent values, frequency descending, ties broken by smaller value.
- Count with a dict / Map first — one pass.
- Then sort the distinct values by (-count, value) and take the first k.
- The tie-break is exactly what the tuple sort key encodes.
- For the O(n) flex: bucket values by count (counts are ≤ n), then walk buckets high to low.
Explore the topic
See this challenge alongside everything else on the same subject — handbooks, system designs, algorithms and tools, in one place.