◀ THE GRIND — ARRAYS & HASHING

Top K Frequent Elements

MEDIUM✓ CHIP-TIMEDLC #347 — FULL STATEMENT ↗

The drill: Pull out the k values that appear most often in an array. Every solution counts first; the pace difference is entirely in how you select the winners from the tally — and there is a way to skip the comparison sort altogether.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

An array of integers and a count k arrive together, and the task is to report the k values that occur most often across the whole array.

Ties in frequency don't need any particular tiebreak — as long as exactly k values come back and each one genuinely belongs among the most frequent, the order of the result is free.

On this course, k is always small enough, and the array varied enough, that exactly k distinct values can be identified as the answer without ambiguity over who belongs.

EX 01
nums = [4, 4, 4, 6, 6, 2] · k = 2
[4, 6]
COUNTS 3, 2, 1 - CLEAN PODIUM
EX 02
nums = [7] · k = 1
[7]
FIELD OF ONE
EX 03
nums = [3, 3, 3, 3] · k = 1
[3]
ONE VALUE OWNS THE WHOLE ARRAY
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Tally first — that part is forced. The open question is selecting the k largest counts without ordering everything.

HINT 2 THE STRUCTURE

A frequency is an integer between 1 and n. Values drawn from a small known range can be sorted by address instead of by comparison — that is a bucket sort.

HINT 3 ONE STEP FROM THE ANSWER

Build bucket[f] = the values occurring exactly f times, then read the buckets from f = n downward, collecting until you hold k values.

COACH'S BOARD — THE PATTERN, STEP BY STEP
BUCKETS BY COUNTPATTERN · FREQUENCY BUCKETSnums = [4, 4, 4, 6, 6, 2] · k = 2
4
4
4
6
6
2
TALLY / BUCKETS
— empty —
STEP 1

nums = [4, 4, 4, 6, 6, 2], k = 2. Tally frequencies first, then bucket by count instead of sorting.

STEP 1 / 9 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/top-k-frequent-elements.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        freq = collections.Counter(nums)
        buckets = [[] for _ in range(len(nums) + 1)]  # buckets[f]: values seen f times
        for v, f in freq.items():
            buckets[f].append(v)
        ans = []
        for f in range(len(nums), 0, -1):  # sweep from the top bucket down
            for v in buckets[f]:
                ans.append(v)
                if len(ans) == k:
                    return ans
        return ans
TIME O(N)SPACE O(N)PYTHON · RACE PACE · 13 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED