2Brute2Best
🔥0

Top K Frequent Elements

Medium·LeetCode #347Basic Anchor
LeetCode
30-Second Mental ModelTop K by frequency — count map, then a size-k heap or buckets by count
Complexity:O(N + U log U)→O(N)
Key Insight

A count can't be bigger than n, so use the count as the bucket index. bucket[c] lists the values that appear exactly c times. Walk the buckets from n down to 1 and stop once you have k values. No sorting and no heap are needed.

Core Validity Invariant

Each value sits in the bucket for its exact count, so the highest non-empty buckets hold the most frequent values.

01

Problem

You get an array of integers nums and a number k. Count how often each value appears. Return the k values that appear the most.

The order of the answer does not matter. The problem promises one correct answer: the k-th most frequent value always appears strictly more often than the next one.

Input

An integer array nums, and an integer k.

Output

A list of k values: the most frequent ones. Any order is fine.

Example 1
Input: nums = [1, 1, 1, 2, 2, 3], k = 2
Output: [1, 2]

1 appears 3 times and 2 appears 2 times. 3 appears only once, so it is not in the answer.

Example 2
Input: nums = [1], k = 1
Output: [1]

There is only one value.

Example 3
Input: nums = [1, 2, 1, 2, 1, 2, 3, 1, 3, 2], k = 2
Output: [1, 2]

1 appears 4 times, 2 appears 4 times, and 3 appears 2 times. The top two are 1 and 2.

Constraints
  • • 1 ≤ nums.length ≤ 10^5
  • • −10^4 ≤ nums[i] ≤ 10^4
  • • 1 ≤ k ≤ the number of unique values in nums
  • • The answer is unique (the problem guarantees it).
  • • Follow-up: can you do better than O(n log n)?
02

First, think yourself

Before opening any solution, try to answer these on paper. Use hints only when stuck — each hint is counted.

  1. 1.

    Does the question ask about the values themselves, or about how often each value appears?

  2. 2.

    Can I answer it without sorting every value? What is the smallest thing I need to keep?

  3. 3.

    If I keep only the best k candidates, should I compare them by the value or by the count?

  4. 4.

    How many times can one value appear in an array of length n?

  5. 5.

    Can two values with the same count both belong in the answer? Give a small example.

03

Brute force approach

04

Better approach

05

Optimized approach

06

Why does this algorithm work?

07

Dry run

08

All approaches compared

ApproachIdeaTimeSpace
Brute ForceCount the values, sort all (count, value) pairs, take the first kO(N + U log U)O(U)
BetterCount the values; keep a min-heap of at most k (count, value) pairs, keyed on the countO(N + U log k)O(U)
OptimalCount the values; put each value in the bucket for its count; walk from the highest bucket downO(N)O(N)
09

Why does this belong to this pattern?

Clues in the problem statement
  • “k most frequent”Count first. The number that matters is the count, not the value.
  • “return the k values”Keep only k candidates: a heap of size k, or buckets walked from the top.
  • “any order”No sort is needed. A heap or a bucket walk gives the set directly.
  • “the answer is unique”No tie at the k-th place, so no tie-break rule is needed.
Count each value+keep the k best by count+count ≤ n → bucket by count→Top K by frequency — count map, then a size-k heap or buckets by count

Kth Largest picks by the value itself. This question picks by how often each value appears, so the key is the count, not the value. A value that appears three times beats a value 9 that appears once. Sort Characters By Frequency reuses the count step, but it needs every character, not only the top k.

10

Don't make this mistake

Pattern confusion: keying the heap on the value
✗ priority_queue<int, vector<int>, greater<int>> heap; // a heap of values
✓ priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> heap; // (count, value)

On nums = [1, 1, 1, 2, 2, 3, 4, 4, 5] with k = 3, a heap of values keeps the three biggest numbers: 3, 4 and 5. The right answer is 1, 2 and 4, because 1 appears 3 times and 2 and 4 appear 2 times each. The heap must compare the count, not the value.

Using the value as the bucket index
✗ bucket[value].push_back(value);
✓ bucket[count].push_back(value);

Values can be negative (down to −10^4), so bucket[value] is out of range. A bucket index is a count, which is always between 0 and n.

Walking the buckets from the bottom up
✗ for (int c = 1; c <= n; c++)
✓ for (int c = n; c >= 1; c--)

Walking up collects the least frequent values first. On nums = [1, 1, 1, 2, 2, 3, 4, 4, 5] with k = 3, it takes 3 and 5 (count 1) first, then one count-2 value. The answer must be 1, 2 and 4.

11

Want to implement this?

Write it yourself on LeetCode, then come back and compare your code with the solutions above.

Open coding workspace
How did it go?
Beyond The LeetCode Problem

How this concept connects to System Design & C++ Systems

Bridge DSA with production engineering

Top engineering interviews test whether you understand how algorithms like Heap — Top K translate into production architectures and low-level memory mechanics.