Top K Frequent Elements - JS Solution

JS
Editorial

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.

  1. 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.
  2. 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.
  3. 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.

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.