function topKFrequent(nums, k) {const count = new Map();◄
for (const n of nums) count.set(n, (count.get(n) || 0) + 1);
const buckets = Array.from({length: nums.length+1}, () => []);for (const [n, c] of count) buckets[c].push(n);
const res = [];
for (let c = buckets.length-1; c > 0 && res.length < k; c--)
for (const n of buckets[c]) {res.push(n);
if (res.length === k) return res;
}
return res;
}
First tally how many times each value occurs using a hash map.
The highest frequency any value can have is the array length, so make one bucket per possible frequency.
Drop each value into the bucket matching its count — this groups by frequency without sorting (no n·log n).
Walk the buckets from the highest frequency downward, collecting values until you have k.