Top K Frequent Elements

Find the k most frequent elements using sorting, a min-heap, or bucket sort.

Top K Frequent Elements

Problem: Given an array of numbers, return the k most frequently occurring elements. The answer can be in any order.

Example:

  • Input: nums = [1, 1, 1, 2, 2, 3], k = 2
  • Output: [1, 2] (1 appears 3 times, 2 appears 2 times — those are the top 2)

Note

First count how many times each number appears. Then figure out which k numbers appeared the most.


Brute Force — Count + Sort


Optimal — Min Heap of Size k


Best — Bucket Sort


ApproachTimeSpaceNotes
Sort by frequencyO(n log n)O(n)Simple, easy to write
Min Heap of size kO(n log k)O(n)Better when k is small
Bucket SortO(n)O(n)Fastest — uses frequency as index

LeetCode 347 — Top K Frequent Elements