Editorial solutions and visualizations are prepared with care, but we do not guarantee 100% accuracy or completeness. Please use your own judgment to verify results. Visucodize is not responsible for decisions made based on this content.
Solution code
constCURRENT_FREQ='current_freq',CURRENT_FREQ_COLOR='blue';functionvisMainFunction(nums, k){initClassProperties();explanationAndColorSchemaNotifications();
VisArray.from(nums).options({label:'nums'}).createVis();// Step 1: Frequency MapstartPartialBatch();startBatch();const freqMap =newVisMap();for(const num of nums){const count =(freqMap.get(num)||0)+1;
freqMap.set(num, count);}endBatch();notification(`
🔢 <b>Step 1:</b> Count frequencies of all numbers.<br><br>
We built a <b>frequency map</b> where each key is a number from <b>nums</b>
and each value represents how many times it appears.<br><br>
These frequencies will be utilized to determine which elements are the top ${k} frequent elements.
`);endBatch();// Step 2: MinHeap to keep top K elementsstartPartialBatch();notification(`
📦 <b>Step 2:</b> Initialize a <b>MinHeap</b> (MinPriorityQueue)
to dynamically maintain the <b>top ${k}</b> most frequent elements as we traverse the frequency map
(initially, it holds fewer entries until we have processed at least <b>${k}</b> unique numbers).<br><br>
The heap stores <code>{ num, freq }</code> pairs, always keeping the entry with the
<b>smallest frequency</b> at the top — representing the least frequent element
among the current top candidates.<br><br>
Whenever the heap exceeds size <b>${k}</b>, we remove that least frequent entry to ensure
it continues to hold only the <b>top ${k}</b> most frequent elements seen so far.
`);// Note that the MinPriorityQueue library version used by Leetcode accepts it as MinPriorityQueue((entry) => entry.freq)const heap =newVisMinPriorityQueue({priority:(entry)=> entry.freq }).options({labelExtractionPolicy:(entry)=>`n=${entry.num},f=${entry.freq}`});for(const[num, freq]of freqMap.entries()){const keyVisManager = freqMap.makeVisManagerForKey(num);
keyVisManager.addClass(CURRENT_FREQ);notification(`
📥 Checking frequency of <b>${makeColoredSpan(num,CURRENT_FREQ_COLOR)}</b>:
appears <b>${freq}</b> time${freq >1?'s':''}.<br><br>
Inserting { num: ${num}, freq: ${freq} } into the MinHeap.
`);
heap.enqueue({ num, freq });if(heap.size()> k){notification(`
⚖️ The heap size exceeded <b>${k}</b> after this insertion.<br><br>
We'll call <code>dequeue()</code> to remove the <b>least frequent entry</b> —
the one currently at the top of the MinHeap — ensuring that only the
<b>top ${k}</b> most frequent elements</b> remain in the heap.
`);
heap.dequeue();}
keyVisManager.removeClass(CURRENT_FREQ);}endBatch();notification(`
📤 <b>Step 3:</b> Extracting all remaining elements from the heap.<br><br>
We’ll now read each { num, freq } pair from the heap to form the final result list.<br>
Since the heap holds only the top ${k} most frequent numbers,
all extracted values belong to the answer set.
`);// Note that for the MinPriorityQueue version used by leetcode should map to entry.num instead const result = heap.toArray().map(entry=> entry.element.num);
VisArray.from(result).options({label:'result'}).createVis(true);notification(`
🏁 <b>Result complete!</b><br>
The <b>top ${k}</b> most frequent elements have been extracted from the MinHeap
and placed into the <code>result</code> array.<br><br>
The order may vary depending on heap internals, but since the problem allows any order,
the result is valid and ready to return.
`);return result;}functionexplanationAndColorSchemaNotifications(){explanationNotification();notification(`
🎨 <b>Color Schema</b><br><br>
🟦 <b>${makeColoredSpan('Current entry in frequency map',CURRENT_FREQ_COLOR)}</b> — the <b>frequency entry</b> that is currently being processed.
`);}functioninitClassProperties(){setClassProperties(CURRENT_FREQ,{backgroundColor:CURRENT_FREQ_COLOR});}
Solution explanation
Solution explanation
Approach
We need to find the top k most frequent numbers in nums.
The solution combines a frequency map and a MinHeap (MinPriorityQueue) for efficient tracking of the top k elements.
Step 1: Count frequencies.
Traverse the input array once and build a hashmap that records how many times each number appears.
This gives us a clear frequency distribution — each entry is a (num, freq) pair.
Step 2: Maintain a running Top-K set using a MinHeap.
Iterate through the frequency map and push each { num, freq } pair into a MinHeap
whose priority is based on freq.
Initially, the heap holds fewer entries until we have processed at least k unique numbers.
The heap always keeps the smallest frequency at the top, representing the least frequent element
among the current top candidates.
Whenever the heap size exceeds k, we call dequeue() to remove the least frequent entry,
ensuring the heap continuously maintains only the top-k most frequent elements seen so far.
Step 3: Extract results.
After processing all entries, the heap contains the top-k most frequent entries,
each in the form of an object { num, freq }.
We then extract each entry’s num field to form the final list of numbers.
Since the problem allows any order, we can simply use heap.toArray()
to retrieve all entries and return their num values as the final answer.
Why It Works
The frequency map ensures every number’s count is computed in O(N) time.
The MinHeap keeps only k elements at all times, efficiently discarding
lower-frequency ones as new entries come in.
This guarantees that the heap always holds the current top-k most frequent numbers,
and no extra work is needed at the end to sort or filter.
Time Complexity
Let N be the length of the input array and U be the number of unique elements.
Building the frequency map takes O(N).
Each heap operation (enqueue/dequeue) takes O(log k),
and we perform these operations once per unique number, giving O(U log k) overall.
Combined, the total time complexity is O(N + U log k).
Space Complexity
Let N be the length of the input array and U be the number of unique elements.
The frequency map stores up to U entries, and the heap holds at most k elements,
resulting in O(U + k) auxiliary space.
Input-1
Visucodize editorial solution titled JS Solution for LeetCode's Top K Frequent Elements coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/top-k-frequent-elements.