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
- Declare
countas 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. - Loop over
numswithfor...of, so eachnumadds one to its own count. - Add 1:
count[num] = (count[num] || 0) + 1. A value seen for the first time has no key yet, socount[num]isundefined, and|| 0turns that into 0. - Create
buckets,nums.length + 1empty arrays, withArray.from({ length: nums.length + 1 }, () => []). The arrow function runs once per item, so every bucket gets its own array. The extra slot lets indexnums.lengthexist. - Loop over
Object.entries(count), destructuring each entry into[num, freq]: the value and its count. - Push into the bucket
buckets[freq]. Object keys are strings, soNumber(num)turns the value back into a number. - Declare
resultas an emptynumber[]. - Start
freqatnums.length, the highest possible count, withletbecause it changes. - Loop while
result.length < k. Each pass takes one bucket. - 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 pastkvalues. - Decrement
freqto move to the next lower count. - 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 writecount[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 withNumber(num). Without it, the answer would be an array of strings, even though it is typednumber[], because types are erased at run time. - Negative numbers work as keys. The key for -1 is the string
"-1", andNumber("-1")gives back -1. Array.from({ length: n }, fn)buildsnitems by callingfnfor 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'sfreqis scoped to that loop. The laterlet freqis 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
Mapwould also work for counting and would keep numeric keys, which removes the need forNumber(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, notfill([]). - Buckets of size
nums.length. A value can appearnums.lengthtimes, as in[5, 5, 5, 5], so indexnums.lengthmust exist. That is the reason for the+ 1. - Ties at the cut. The lesson guarantees none. Without that guarantee, a bucket could push
resultpastk:[4, 4, 1, 1, 2]withk = 1returns[1, 4], two values. - Sorting by count. Correct, but it is
O(n log n). Also, callingsort()on numbers without a compare function orders them as text:[10, 9, 1].sort()gives[1, 10, 9]. - One value only.
[1]withk = 1returns[1].
Testing
nums = [1, 1, 1, 2, 2, 3],k = 2gives[1, 2].nums = [1],k = 1gives[1].nums = [4, -1, 4, -1, 7, 4, -1, 9],k = 2gives[4, -1].nums = [5, 5, 5, 5],k = 1gives[5].nums = [3, 3, 2, 2, 2, 1],k = 1gives[2].
