← DSA
MEDIUM

Top K Frequent Elements

PracticeNeetCode ↗LeetCode ↗

Given an integer array nums and an integer k, return the k most frequent elements. The answer can be in any order.

Example

Input nums = [1,1,1,2,2,3], k = 2
Output [1,2]

Key Pointers

Step-by-Step Analysis

  1. Count each number's frequency with a hashmap.
  2. Create buckets, an array of length n+1, where buckets[f] holds every number with frequency f.
  3. Place each number into buckets[count[num]].
  4. Walk buckets from index n down to 1, collecting numbers into the result until it has k elements.

Complexity

Time: O(n) — Space: O(n)

Code

def topKFrequent(nums: list[int], k: int) -> list[int]:
    count = {}
    for n in nums:
        count[n] = count.get(n, 0) + 1

    buckets = [[] for _ in range(len(nums) + 1)]
    for n, freq in count.items():
        buckets[freq].append(n)

    result = []
    for freq in range(len(buckets) - 1, 0, -1):
        for n in buckets[freq]:
            result.append(n)
            if len(result) == k:
                return result
    return result

Code Explanation

How the solution above works, piece by piece.

  1. First loop: count how often each number appears.
  2. buckets = [[] for _ in range(len(nums) + 1)]: index = frequency. No number can appear more than len(nums) times, so this is always big enough.
  3. buckets[freq].append(n): file each number under its count. This replaces sorting by frequency, which would cost O(n log n).
  4. Walk freq from high to low and collect numbers until k are gathered, then return.
  5. Every step is linear: O(n) time and O(n) space. That's the bucket-sort trick: frequencies are small integers, so they can be array indices.

Visual Walkthrough

Running it on nums = [1, 1, 1, 2, 2, 3], k = 2:

Counting then bucketing by frequency for top 2 frequentnums111223count1:32:23:1buckets0312213456index = frequency12scan from the high endresult = [1, 2] after 2 picks (k = 2)
Count each number, then drop each number into the bucket whose index is its frequency. Walking the buckets from the highest index down gives the most frequent numbers first; the amber badges show the pick order.
1 (appears 3×)2 (appears 2×)

Video Explanation

NeetCode — Top K Frequent Elements, Bucket Sort, LeetCode 347