ALGORITHMS
🇬🇧UK Edition🇨🇦Canada Edition🌐Global Tech

Top K Frequent Elements: Min-Heap vs Bucket Sort Solutions

Elena Rostova
Elena Rostova
Staff Engineer & Algorithmic Specialist
Updated 03/09/20265 min read0 views

Bucket Sort Approach for O(N) Time

Count element frequencies using a hash map, then group elements into buckets indexed by frequency count.

python
from collections import Counter

def top_k_frequent(nums, k):
    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

print(top_k_frequent([1, 1, 1, 2, 2, 3], 2))

Frequently Asked Questions (FAQ)

Q: When is Min-Heap preferable over Bucket Sort?

When processing streaming data where total array length N is unknown.

Elena Rostova
Written by Elena RostovaAdSense EEAT Verified

Staff Engineer & Algorithmic Specialist. Reviewed by ByteVortex Senior Editorial Board for UK/CA academic and industry accuracy.