Top K Frequent Elements

Return the k most frequent elements.

Pattern

Bucket Sort / Heap

This problem follows the Bucket Sort / Heap pattern, commonly found in the Arrays & Hashing category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Count frequencies, then use bucket sort where index = frequency.

Key Insight

Bucket sort by frequency avoids the O(n log n) of sorting — since frequency can be at most n, you get O(n) time.

Step-by-step

  1. 1Count the frequency of each element using a hash map
  2. 2Create buckets where index = frequency (size n+1)
  3. 3Place each element into the bucket matching its frequency
  4. 4Iterate buckets from highest to lowest, collect k elements

Pseudocode

count = Counter(nums)
buckets = [[] for _ in range(len(nums) + 1)]
for num, freq in count.items():
    buckets[freq].append(num)
result = []
for i in range(len(buckets) - 1, 0, -1):
    for num in buckets[i]:
        result.append(num)
        if len(result) == k: return result
Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(n)
More Arrays & Hashing Problems

Master this pattern with YeetCode

Practice Top K Frequent Elements and similar Arrays & Hashing problems with flashcards. Build pattern recognition through active recall.

Practice this problem