#347

Top K Frequent Elements

Medium Bucket sort by frequency

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the k most frequent values in the array (the answer is unique).

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the k values that appear most.

Why this works: count, then bucket values by count (counts are ≤ n) and read buckets from the top.

Example: [1, 1, 1, 2, 2, 3], k = 2

counts 1→3, 2→2, 3→1buckets: 3:[1], 2:[2] → [1, 2]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Sorting all map entries by frequency — O(n log n), fine but not the best.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(n).
Topic: Heaps & Priority Queue
🎬 Episodes 64–68: video coming soon