DSA AnimatorDSA animations
Top K Frequent Elements LC #347 Medium Min-Heap · Frequency Map
Problem

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

Example 1
Input: nums=[1,1,1,2,2,3], k=2
Output: [1, 2]
1 appears 3×, 2 appears 2×.
Example 2
Input: nums=[1,2,2,3,3,3], k=2
Output: [2, 3]
3 appears 3×, 2 appears 2×.
Example 3
Input: nums=[4,4,4,6,6,1,1,1,1], k=2
Output: [1, 4]
1 appears 4×, 4 appears 3×.
Constraints: 1 ≤ nums.length ≤ 10⁵  |  k is in [1, number of unique elements]  |  answer is guaranteed unique
Try Examples
Custom:
Approach
Count frequencies with HashMap, then use a Min-Heap of size k
If heap grows > k, remove the minimum. Result = remaining k elements
Input Array
Frequency Map
Load an example to begin.
Not yet in heap
Currently adding
In heap (candidate)
Heap minimum (root)
Evicted
Top-k result
Min-Heap (by frequency) size: 0 / k
 min-freq root
Heap is empty
Variables
Current elem
—
Its freq
—
Heap size
0
k
—
Step Logic
Press ▶ Play or Next Step to begin.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Build frequency map: count occurrences of each element — O(n)
2
Create a min-heap ordered by frequency (lowest freq = root)
3
For each unique elem: minH.offer(elem, freq)
4
If minH.size() > k: minH.poll() — evict least-frequent
5
Remaining heap elements are the top-k — return them
Time
O(n log k)
Space
O(n)
Why Min-Heap of Size k?

We want the k largest frequencies. By keeping a min-heap capped at size k, the root is always the weakest current candidate (lowest frequency among our best k so far). When a new element arrives and makes the heap k+1, we evict the root — guaranteed to be the least-valuable. After all unique keys are processed, the heap holds exactly the answer. Runs in O(n log k) vs. O(n log n) for full sort.

How to solve Top K Frequent Elements

LeetCode 347 · Medium · Heap / Priority Queue · Pattern: Count + Min Heap

Why the obvious approach is slow

You could count the frequencies, then sort all distinct values by frequency. That is O(n log n). With a heap of size k, we only keep the best k candidates.

The key idea

First, count every value with a hash map. Then go through the map, and push each value into a min heap ordered by frequency. If the heap grows beyond k, poll the root, which is the least frequent value in it. At the end, the heap holds exactly the k most frequent values.

Remember

Count first, then keep the top k with a min heap. Bucket sort by frequency is the O(n) alternative.

Run the animation above on your own input, or watch the 1:47 video explanation of Top K Frequent Elements with a dry run and Java code.

More Heap / Priority Queue problems