Hashing: top K frequent elements
Hashing: top K frequent elements
Given a list of numbers, return the k values that show up most often
(LeetCode #347). The natural first step is counting, and a hash map (a
dict) is built for exactly this β one O(n) pass and you know how many times
every value appears.
counts = {}
for x in nums:
counts[x] = counts.get(x, 0) + 1
# counts == {1: 3, 2: 2, 3: 1} for nums == [1,1,1,2,2,3]
Once you have the counts, you sort the distinct values to pick the top k.
Deterministic ordering (important)
Ties in frequency are common, so we pin down an exact order to keep results reproducible:
- sort by frequency, descending (most frequent first);
- break ties by value, ascending (smaller number first).
Then return the first k values as a list. For [4,4,5,5,6] with k=2,
both 4 and 5 appear twice β the tie-break by value puts 4 before 5, so
the answer is [4, 5], never [5, 4].
Your task
Write top_k_frequent(nums, k) returning a list of the k most frequent
values, ordered by frequency descending then value ascending.
top_k_frequent([1,1,1,2,2,3], 2) # [1, 2]
top_k_frequent([1], 1) # [1]
top_k_frequent([4,4,5,5,6], 2) # [4, 5] (tie broken by value)
top_k_frequent([7,7,8,8,9], 3) # [7, 8, 9]
Hint: a sorted(..., key=lambda v: (-counts[v], v)) sorts by descending
frequency and ascending value in one shot, because negating the count flips
its sort direction.
Tests
- two most frequent
- single element
- tie broken by value
- all three
- k equals one tie (hidden)
- clear winner (hidden)
Stuck? Ask for a spark
$ Console output will appear here.