Top K Frequent Elements

MediumHeap · Bucket Sort · Top K🧩 Heap & Top-KLeetCode #347 ↗Updated

Problem

You are given an integer array nums and an integer k. Return the k values that occur most often in nums, in any order. The input guarantees that the answer is unique.
Input[1,1,1,2,2,3], k=2Output[1,2]
Input[1], k=1Output[1]

1 ≤ n ≤ 105  ·  -104 ≤ nums[i] ≤ 104  ·  1 ≤ k ≤ #distinct  ·  Follow-up: beat O(n log n).

Try it yourself

Java
class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
A frequency is an integer between 1 and n. So instead of sorting by frequency, drop each value into bucket freq and read buckets from high to low — a counting sort that runs in linear time.
PatternHeap & Top-K

Instinct "K largest / smallest / closest / most frequent", or "always take the best available next"? Keep a heap - size k for top-K, or a ready-queue for scheduling.

Memory hack Guard the top-K club with a bouncer - a min-heap of size k whose root is the weakest member; anyone stronger kicks them out.

Open the Heap & Top-K guide →

Approaches

Brute ForceCount + Sort by Frequency

Time O(n log n)Space O(n)

Count occurrences with a hash map, sort the distinct values by count descending, and take the first k. Sorting all m ≤ n distinct values does far more work than needed when k is small.

Java
public int[] topKFrequent(int[] nums, int k) {
    Map<Integer, Integer> count = new HashMap<>();
    for (int x : nums) count.merge(x, 1, Integer::sum);
    List<Integer> keys = new ArrayList<>(count.keySet());
    keys.sort((a, b) -> count.get(b) - count.get(a));
    int[] result = new int[k];
    for (int i = 0; i < k; i++) result[i] = keys.get(i);
    return result;
}

Simple and correct, but fails the follow-up (O(n log n)).

At a glance

LevelApproachTimeSpace
Brute ForceCount + Sort by FrequencyO(n log n)O(n)
BetterCount + Min-Heap of Size kO(n log k)O(n)
OptimalCount + Bucket Sort by FrequencyO(n)O(n)
Common pitfalls
  • Bucket array of size n instead of n + 1 — a value seen n times overflows.
  • Using a max-heap of all values — O(n log n) again; keep a size-k min-heap.
  • Not stopping at exactly k inside a bucket holding several values.
Interview tips
  • Clarify that order doesn't matter and the answer is unique.
  • Walk sort → heap → buckets, stating each complexity.
  • Point out frequencies are bounded by n — that's what enables counting sort.
Pattern
Frequency count + heap/bucket → “k most/least frequent” or top-k by a bounded integer key.
My notes saved in this browser