Skip to content
ΣDSA Patterns
Menu
Language

Hashing

Guide 6 of 6 · Path 6 of 6

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 8
1
1
1
2
2
3
map132231

K = 2

Top K frequent. Count frequencies first.

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

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 only
Time 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