Start learning free

LESSON 85 OF 314 · HASH TABLE

Top K Frequent Elements in TypeScript: 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

    TYPESCRIPT · HASH TABLE

    Top K Frequent Elements in TypeScript, explained

    Problem overview

    The method topKFrequent receives an array of numbers, nums, and a number k. It returns the k values that appear most often in nums, in any order. The frequency of a value is the number of times it appears. The answer is guaranteed to be unique: every value in it appears more often than every value left out, so there are no ties at the cut. The algorithm must run in O(n) time with O(n) extra space.

    For nums = [1, 1, 1, 2, 2, 3] and k = 2, the value 1 appears 3 times, 2 appears twice and 3 once, so the answer is [1, 2]. For [4, -1, 4, -1, 7, 4, -1, 9] with k = 2, the values 4 and -1 both appear three times, and the method returns [4, -1]; [-1, 4] would be correct too.

    Approach: count, then bucket by count

    The first step is to count every value with a hash table, which takes one pass over the array. The usual next step is to sort the values by count, but that costs O(n log n), and the lesson asks for O(n).

    The way out is that a count can't be larger than nums.length. So instead of comparing counts, give every possible count its own bucket: buckets[f] holds the values that appear exactly f times. Putting each distinct value in its bucket costs constant time, with no comparisons between counts. Then read the buckets from the highest count down, collecting values until there are k of them.

    On [1, 1, 1, 2, 2, 3] the counts are 1 appearing 3 times, 2 twice and 3 once. The buckets, for counts 0 to 6, are:

    [[], [3], [2], [1], [], [], []]
    

    Reading from index 6 down finds 1 first, then 2: with k = 2 the answer is [1, 2].

    Step by step

    1. Declare count as an empty object typed { [key: number]: number }. It maps each value to how many times it appears. An object works as a hash table, with constant-time lookups.
    2. Loop over nums with for...of, so each num adds one to its own count.
    3. Add 1: count[num] = (count[num] || 0) + 1. A value seen for the first time has no key yet, so count[num] is undefined, and || 0 turns that into 0.
    4. Create buckets, nums.length + 1 empty arrays, with Array.from({ length: nums.length + 1 }, () => []). The arrow function runs once per item, so every bucket gets its own array. The extra slot lets index nums.length exist.
    5. Loop over Object.entries(count), destructuring each entry into [num, freq]: the value and its count.
    6. Push into the bucket buckets[freq]. Object keys are strings, so Number(num) turns the value back into a number.
    7. Declare result as an empty number[].
    8. Start freq at nums.length, the highest possible count, with let because it changes.
    9. Loop while result.length < k. Each pass takes one bucket.
    10. Add the whole bucket with result.push(...buckets[freq]). The spread syntax passes the bucket's values as separate arguments. Because the answer is unique, a bucket never pushes the result past k values.
    11. Decrement freq to move to the next lower count.
    12. Return result.

    The solution in TypeScript

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

    Some TypeScript details:

    • Keys of an object are strings. The type { [key: number]: number } lets you write count[4], but at run time the key is the string "4". Object.entries(count) for the first example gives [["1", 3], ["2", 2], ["3", 1]]. That is why the lesson converts with Number(num). Without it, the answer would be an array of strings, even though it is typed number[], because types are erased at run time.
    • Negative numbers work as keys. The key for -1 is the string "-1", and Number("-1") gives back -1.
    • Array.from({ length: n }, fn) builds n items by calling fn for each. new Array(n).fill([]) would put one shared array in every slot, so pushing into one bucket would appear in all of them: new Array(3).fill([]) after one push shows [[1], [1], [1]].
    • Two variables named freq. The loop's freq is scoped to that loop. The later let freq is a separate variable declared after it, so there is no clash.
    • Spread in push. result.push(...bucket) adds each element of the bucket. An empty bucket adds nothing.
    • A Map would also work for counting and would keep numeric keys, which removes the need for Number(num). The lesson uses an object, as above.

    Complexity

    Time: O(n). Counting is one pass. Filling the buckets visits each distinct value once. The final loop looks at no more than n buckets, and the values it copies add up to at most k.

    Space: O(n). The count object has at most n keys, and the buckets array has n + 1 slots holding at most n values in total.

    Edge cases and common mistakes

    • Forgetting Number(num). The values come back as strings.
    • Sharing one empty array between buckets. Use a function in Array.from, not fill([]).
    • Buckets of size nums.length. A value can appear nums.length times, as in [5, 5, 5, 5], so index nums.length must exist. That is the reason for the + 1.
    • Ties at the cut. The lesson guarantees none. Without that guarantee, a bucket could push result past k: [4, 4, 1, 1, 2] with k = 1 returns [1, 4], two values.
    • Sorting by count. Correct, but it is O(n log n). Also, calling sort() on numbers without a compare function orders them as text: [10, 9, 1].sort() gives [1, 10, 9].
    • One value only. [1] with k = 1 returns [1].

    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 = [5, 5, 5, 5], k = 1 gives [5].
    • nums = [3, 3, 2, 2, 2, 1], k = 1 gives [2].
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free