Mediumhashing
Top K Frequent Elements
Problem (restated)
Return the k most frequent elements in any order.
Intuition
Count frequencies, then bucket by frequency so the densest buckets are at the end.
Approaches
Frequency buckets
Tested onlyTime O(n)Space O(n)
Idea. Map value→count. buckets[c] holds values with count c. Scan buckets from high to low.
Walkthrough. [1,1,1,2,2,3], k=2 → 1 has freq 3, 2 has 2 → [1,2].
Trade-offs. Heap is O(n log k). Buckets hit average O(n) with integer frequencies.
Solution
export function topKFrequent(nums: number[], k: number): number[] {
const freq = new Map<number, number>();
for (const x of nums) freq.set(x, (freq.get(x) ?? 0) + 1);
const buckets: number[][] = Array.from({ length: nums.length + 1 }, () => []);
for (const [val, c] of freq) buckets[c]!.push(val);
const out: number[] = [];
for (let c = buckets.length - 1; c >= 0 && out.length < k; c--) {
for (const v of buckets[c]!) {
out.push(v);
if (out.length === k) return out;
}
}
return out;
}
export function topKFrequent(nums: number[], k: number): number[] {
const freq = new Map<number, number>();
for (const x of nums) freq.set(x, (freq.get(x) ?? 0) + 1);
const buckets: number[][] = Array.from({ length: nums.length + 1 }, () => []);
for (const [val, c] of freq) buckets[c]!.push(val);
const out: number[] = [];
for (let c = buckets.length - 1; c >= 0 && out.length < k; c--) {
for (const v of buckets[c]!) {
out.push(v);
if (out.length === k) return out;
}
}
return out;
}
Reflection
- Which cue made you pick this pattern in under 90 seconds?
- What input would break a wrong invariant?