Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — Arrays & Hashing

Top K Frequent Elements

MEDIUM✓ CHIP-TIMEDLC #347 — FULL STATEMENT

The briefingthe full drill, in my own words

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.

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.

  • arrays hold up to several thousand elements
  • k is always between 1 and the number of distinct values present
  • ties in frequency don't require a specific tiebreak
  • the k returned values may come back in any order
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 hintstake 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 boardthe 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 splitstwo paces, two languages

grind/top-k-frequent-elements.py — RACE 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-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED