codebrew.ai

Top K Frequent Elements

Count, then select the k largest — a heap or bucket sort beats a full sort.

Approach

Tally frequencies with a hash map. To pick the top k, either push counts into a size-k min-heap (O(n log k)) or bucket-sort by frequency into indices 0..n and read from the top (O(n)). Bucket sort wins when k approaches n.

Time complexity

O(n)

Space complexity

O(n)

Common mistake

Sorting all counts (O(n log n)) when you only need the top k — a heap or buckets is asymptotically better.

See it run, step by step

Generate an interactive lesson for Top K Frequent Elements — trace every variable and watch the algorithm execute until it clicks.

Start a lesson on Top K Frequent Elements

Related problems