Day 13 of 90MediumLeetCode

Top K Frequent Elements

Return the k values that appear most often in the array, in any order.

Pattern
Counting + bucket sort
Time box
20 min
Time
O(n)
Space
O(n)

Try it first — give it 20 minutes

0/4 revealed

Stuck? Take one hint at a time. The struggle is where the pattern sticks.

    The problem in plain English

    Given nums and a number k, return the k values that occur most often. The answer is guaranteed to be unique, and you can return it in any order.

    nums = [1, 1, 1, 2, 2, 3], k = 2 → [1, 2] (1 appears 3 times, 2 appears twice)

    Start with brute force

    1. Count each value with a hash map.
    2. Sort the distinct values by count, largest first.
    3. Take the first k.

    That's O(n log n) because of the sort. It's a fine first answer — say it, then improve it.

    Building the intuition

    There are three levels of answer here, and walking an interviewer through them is a great signal:

    1. Sort by count — O(n log n).
    2. Min-heap of size k — keep only the k best counts seen so far; anything smaller gets popped. O(n log k). Great when k is tiny compared to n.
    3. Bucket sort — O(n). This is the key observation: a value can appear at most n times. So counts live in the small range 1…n, and we can use the count itself as an array index instead of comparing counts.

    Picture n + 1 shelves labelled 0 to n. Put each value on the shelf matching its count. Then walk the shelves from the top down, collecting values until you have k.

    The optimal approach

    1. Count frequencies: count[value] = times it appears.
    2. Create buckets, a list of n + 1 empty lists.
    3. For each (value, c) in count, append value to buckets[c].
    4. Walk c from n down to 1, adding values from buckets[c] to the answer until it has k values.

    The code

    Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.

    from collections import Counter
    
    
    class Solution:
        def topKFrequent(self, nums: List[int], k: int) -> List[int]:
            count = Counter(nums)                     # value -> how many times
    
            # buckets[c] = values that appear exactly c times (c can be 0..n)
            buckets = [[] for _ in range(len(nums) + 1)]
            for value, c in count.items():
                buckets[c].append(value)
    
            result = []
            for c in range(len(nums), 0, -1):         # most frequent first
                for value in buckets[c]:
                    result.append(value)
                    if len(result) == k:
                        return result
            return result

    Dry run

    nums = [1, 1, 1, 2, 2, 3], k = 2, so n = 6

    Counts: {1: 3, 2: 2, 3: 1}

    Buckets (empty ones omitted): buckets[3] = [1], buckets[2] = [2], buckets[1] = [3]

    cbucketanswer after
    6, 5, 4empty[]
    3[1][1]
    2[2][1, 2] → we have k = 2, stop

    Complexity

    • Time: O(n). Counting is O(n), filling buckets is O(number of distinct values) ≤ O(n), and the walk touches at most n + 1 buckets.
    • Space: O(n) for the counts and buckets.

    For comparison: sorting is O(n log n), and the heap is O(n log k) time with O(n + k) space.

    Edge cases and traps

    • k equals the number of distinct values. You return all of them — the loop handles it.
    • All values equal. One bucket at index n holds the single value.
    • Bucket size. You need n + 1 buckets (counts go up to n), not n. Off-by-one here crashes.
    • Stopping mid-bucket. A bucket can hold several values; stop as soon as you've collected k.

    Say it in the interview

    "I count with a hash map first. Sorting by count would be O(n log n), and a size-k min-heap is O(n log k). But counts are bounded by n, so I can bucket sort: bucket i holds the values that appear exactly i times. Reading buckets from n down to 1 until I have k values gives O(n) time and O(n) space."

    Follow-ups interviewers ask

    • "What if it's a never-ending stream?" You can't bucket the whole stream; keep counts and a size-k min-heap.
    • "Top k frequent words, ties broken alphabetically?" (LeetCode 692) Use a heap with a custom comparator.
    • "Which is better in practice, heap or buckets?" Buckets for one-off batch input; the heap when k is small and memory for n buckets is a concern.

    Practise the same idea

    This is Day 13 of a free 90-day plan 🐸

    90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.

    Get the full roadmap — free