← Back to DSA Animator
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.