← Practice
📖 Hash maps and setsLearning path
Browsing as guest·Sign in or create a free account to save progress and use tutor tools.
Lesson·difficulty 3/5·~20 min

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.

python
counts = {}
for ch in "banana":
    counts[ch] = counts.get(ch, 0) + 1
# counts == {'b': 1, 'a': 3, 'n': 2}  — .get(key, 0) defaults a new key to 0

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:

  1. sort by frequency, descending (most frequent first);
  2. 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.

python
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: build the counts, then sorted the distinct values with a two-part key — one part that ranks by how often each value appears (most frequent first), the other by the value itself (smallest first). A classic trick is to negate the count so a single ascending sort flips just that part into descending order.

Tests

  • two most frequent
  • single element
  • tie broken by value
  • all three

✦ Stuck? Ask for a spark

Sign in or create a free account to use your monthly AI explainer allowance.

warming up
Loading editor…
Consolewaiting

$ Console output will appear here.

>_AI coach
Sign in or create a free account to chat with the tutor.