CODING CHALLENGE · N°27

Top-K Frequent Elements

Medium Hash MapHeapsInterview Classic

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.

EXAMPLE 1
Input nums = [1,1,1,2,2,3], k = 2
Output [1, 2]
1 appears 3×, 2 appears 2×
EXAMPLE 2
Input nums = [4,4,5,5,6], k = 2
Output [4, 5]
tie at 2× → smaller value first
EXAMPLE 3
Input nums = [7], k = 1
Output [7]
trivial but a real edge case
CONSTRAINTS
  • 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)).
SOLVE IT YOURSELF

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.

YOUR TASK

Implement top_k_frequent(nums, k) → the k most frequent values, frequency descending, ties broken by smaller value.

HINTS — 4 IDEAS
  1. Count with a dict / Map first — one pass.
  2. Then sort the distinct values by (-count, value) and take the first k.
  3. The tie-break is exactly what the tuple sort key encodes.
  4. For the O(n) flex: bucket values by count (counts are ≤ n), then walk buckets high to low.
CPython · WebAssembly

Explore the topic

See this challenge alongside everything else on the same subject — handbooks, system designs, algorithms and tools, in one place.