Start learning free

LESSON 367 OF 671 · HASH TABLE

Top K Frequent Elements in JavaScript: O(n) with Bucket Sort

Practice O(n) Read the full explanation

You get an array of integers nums and an integer k.

Return the k values that show up most often in nums, in any order.

How often a value shows up is its frequency. The tests always have one clear answer. Every value you return shows up more often than every value you leave out.

 

Example 1:

Input: nums = [5,3,5,8,3,5,2], k = 2
Output: [3,5]
Explanation: 5 shows up 3 times.
3 shows up twice.
8 and 2 show up once each.
The top 2 are 5 and 3. [5,3] is just as correct.

Example 2:

Input: nums = [9,9,9,9], k = 1
Output: [9]
Explanation: 9 is the only value.

Example 3:

Input: nums = [-2,6,-2,0,6,-2,6,1], k = 2
Output: [-2,6]
Explanation: -2 and 6 both show up 3 times.
0 and 1 show up once each.
A tie inside the answer is fine.
Only the values left out must show up less often.

 

Constraints:

  • 1 to 100,000 numbers.
  • Each number is from -10,000 to 10,000.
  • k is at least 1 and at most the number of different values in nums.
  • There is only one correct set of k values.

Note:

Your algorithm should run in O(n) time and use O(n) extra space, where n is the length of nums. Sorting the values by their frequency would already take O(n log n).

STEP 1 OF 12
    Ctrl + Enter to check

    JAVASCRIPT · HASH TABLE

    Top K Frequent Elements in JavaScript, explained

    Problem overview

    The method topKFrequent(nums, k) receives an array of integers and a number k. It returns the k values that appear most often in nums, in any order. A value's frequency is the number of times it appears, and the answer is guaranteed to be unique: every value in it appears more often than every value left out.

    For nums = [1, 1, 1, 2, 2, 3] and k = 2 the answer is [1, 2], since 1 appears three times, 2 twice and 3 once. For nums = [4, -1, 4, -1, 7, 4, -1, 9] and k = 2, the values 4 and -1 appear three times each, so the answer is [4, -1], and [-1, 4] would be correct too.

    Approach: count, then bucket by frequency

    First, count how many times each value appears. An object works as a hash table for this: one pass over nums and a constant-time lookup per value.

    Next, pick the k largest counts. Sorting the values by count would take O(n log n), and the statement asks for O(n). The trick is that a count can't exceed nums.length. So instead of comparing counts, put each value straight into a bucket for its count: buckets[f] holds the values that appear exactly f times. That is a bucket sort.

    The most frequent values then sit in the buckets with the highest indices. Start at index nums.length, walk down one bucket at a time, and add each bucket's values to the result until it holds k values. Empty buckets add nothing. The walk visits at most nums.length buckets, so the whole algorithm is linear.

    On [1, 1, 1, 2, 2, 3] the counts are { '1': 3, '2': 2, '3': 1 }. With seven buckets (indices 0 to 6), the buckets are [[], [3], [2], [1], [], [], []]: 3 appears once, 2 twice and 1 three times. Walking down from index 6, the first two non-empty buckets give 1 and then 2.

    Step by step

    1. Create count as an empty object that maps each value to its number of appearances.
    2. Loop over every num in nums with for...of.
    3. Add one to its count with count[num] = (count[num] || 0) + 1. A value seen for the first time has no key, so count[num] is undefined, and || 0 turns that into 0.
    4. Create buckets with Array.from({ length: nums.length + 1 }, () => []). The arrow function runs once per item, so every bucket gets its own empty array. The extra item makes index nums.length exist, because one value could appear that many times.
    5. Loop over Object.entries(count), destructuring each pair into [num, freq].
    6. Push the value into buckets[freq] as Number(num), because object keys are strings.
    7. Create an empty result.
    8. Start freq at nums.length, the highest possible count, declared with let since it changes.
    9. Loop while result.length < k.
    10. Add the whole bucket with result.push(...buckets[freq]). The spread syntax passes the bucket's values as separate arguments.
    11. Decrement freq to move to the next lower count.
    12. Return result.

    The solution in JavaScript

    class Solution {
        topKFrequent(nums, k) {
            const count = {};
            for (const num of nums) {
                count[num] = (count[num] || 0) + 1;
            }
            const buckets = Array.from({ length: nums.length + 1 }, () => []);
            for (const [num, freq] of Object.entries(count)) {
                buckets[freq].push(Number(num));
            }
            const result = [];
            let freq = nums.length;
            while (result.length < k) {
                result.push(...buckets[freq]);
                freq--;
            }
            return result;
        }
    }
    

    Some JavaScript details worth knowing:

    • Object keys are strings. Writing count[4] stores the key "4", and Object.entries gives it back as the string '4'. That is why the code calls Number(num) before pushing. Without it, the result would hold strings such as '1', which are not equal to the number 1 under ===.
    • count[num] || 0. Reading a missing key gives undefined, not an error. Here || is safe because a real count is never 0, so a stored count is never replaced by the fallback.
    • Array.from({ length: n }, fn) versus fill. new Array(3).fill([]) puts the same array in all three slots: after shared[0].push(1) the result is [[1], [1], [1]]. Array.from with an arrow function calls it once per slot, so the buckets are independent.
    • Order of the keys. Object.entries lists keys that look like non-negative integers first, in ascending order, and other keys, such as '-1', afterwards in insertion order. For the third example the counts have the keys '4', '7', '9' and then '-1', so bucket 3 holds [4, -1]. Since any order is accepted, this only affects how the output looks.
    • Spread in push. result.push(...bucket) adds every value of the bucket as a separate argument, which is shorter than a loop. Here a bucket holds at most the number of distinct values, and the constraints keep that small.

    Complexity

    Time: O(n). Counting is one pass over nums. Building the buckets visits each distinct value once, and creating them takes n + 1 steps. Walking the buckets from the top visits at most n + 1 of them, and each value is pushed once.

    Space: O(n). The count object holds one key per distinct value, and the bucket array has n + 1 slots whose arrays hold each value once.

    Edge cases and common mistakes

    • A single element. [1] with k = 1 returns [1]. The buckets are [[], [1]], and the walk starts at index 1.
    • Every value distinct. [5, 6, 7] with k = 3 returns [5, 6, 7]: all three sit in bucket 1, and the walk goes all the way down to it.
    • One value fills the array. [2, 2, 2, 2] with k = 1 returns [2]. This is why the buckets need nums.length + 1 slots.
    • Negative numbers. [-1, -1, 2, 2, 2, 0] with k = 2 returns [2, -1]. Negative values work as object keys without any special handling.
    • Forgetting Number. The result would contain strings, and a test comparing with numbers would fail.
    • Sharing one empty array between buckets. Building them with fill([]) makes every value land in every bucket.
    • Ties at the cut. The statement guarantees the answer is unique, so the last bucket you take never pushes result beyond k values. Without that guarantee you would have to take only part of that bucket.

    Testing

    • nums = [1, 1, 1, 2, 2, 3], k = 2 gives [1, 2].
    • nums = [1], k = 1 gives [1].
    • nums = [4, -1, 4, -1, 7, 4, -1, 9], k = 2 gives [4, -1].
    • nums = [3, 3, 3, 1, 1, 2], k = 1 gives [3].
    • nums = [10, 9, 9, 10, 10, 8], k = 2 gives [10, 9].
    • nums = [-1, -1, 2, 2, 2, 0], k = 2 gives [2, -1].
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free