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
- Create
countas an empty object that maps each value to its number of appearances. - Loop over every
numinnumswithfor...of. - Add one to its count with
count[num] = (count[num] || 0) + 1. A value seen for the first time has no key, socount[num]isundefined, and|| 0turns that into 0. - Create
bucketswithArray.from({ length: nums.length + 1 }, () => []). The arrow function runs once per item, so every bucket gets its own empty array. The extra item makes indexnums.lengthexist, because one value could appear that many times. - Loop over
Object.entries(count), destructuring each pair into[num, freq]. - Push the value into
buckets[freq]asNumber(num), because object keys are strings. - Create an empty
result. - Start
freqatnums.length, the highest possible count, declared withletsince it changes. - Loop while
result.length < k. - Add the whole bucket with
result.push(...buckets[freq]). The spread syntax passes the bucket's values as separate arguments. - Decrement
freqto move to the next lower count. - 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", andObject.entriesgives it back as the string'4'. That is why the code callsNumber(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 givesundefined, 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)versusfill.new Array(3).fill([])puts the same array in all three slots: aftershared[0].push(1)the result is[[1], [1], [1]].Array.fromwith an arrow function calls it once per slot, so the buckets are independent.- Order of the keys.
Object.entrieslists 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]withk = 1returns[1]. The buckets are[[], [1]], and the walk starts at index 1. - Every value distinct.
[5, 6, 7]withk = 3returns[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]withk = 1returns[2]. This is why the buckets neednums.length + 1slots. - Negative numbers.
[-1, -1, 2, 2, 2, 0]withk = 2returns[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
resultbeyondkvalues. Without that guarantee you would have to take only part of that bucket.
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 = [3, 3, 3, 1, 1, 2],k = 1gives[3].nums = [10, 9, 9, 10, 10, 8],k = 2gives[10, 9].nums = [-1, -1, 2, 2, 2, 0],k = 2gives[2, -1].
