Top K Frequent Elements
Difficulty: Medium · Pattern: Hashing · LeetCode #347
Given an integer array nums and an integer k, return the k values that occur most often. The answer is guaranteed to be unique; return it in any order.
Example
text
nums = [4, 4, 4, 6, 6, 9], k = 2 → [4, 6]
nums = [7], k = 1 → [7]Follow-up: can you do better than O(n log n)?
Hints
- First count every value's frequency with a hash map.
- Sorting by frequency is O(n log n). A heap of size k is O(n log k).
- Frequencies are integers between 1 and n, so you can use them as bucket indices.
Approach
- Count frequencies with a hash map.
- Bucket sort: create
n + 1buckets wherebuckets[f]holds values that occur exactlyftimes. - Walk buckets from high frequency to low, collecting values until you have
k.
That's O(n) overall. A min-heap of size k (push each (freq, value), pop when size > k) gives O(n log k), which is handy when n is huge and k is small.
Complexity
Time: O(n). Space: O(n) for the counts and buckets.
Python solution
from collections import Counter
def topKFrequent(nums, k):
freq = Counter(nums)
buckets = [[] for _ in range(len(nums) + 1)]
for value, f in freq.items():
buckets[f].append(value)
out = []
for f in range(len(buckets) - 1, 0, -1):
for value in buckets[f]:
out.append(value)
if len(out) == k:
return out
return outJavaScript solution
function topKFrequent(nums, k) {
const freq = new Map();
for (const x of nums) freq.set(x, (freq.get(x) || 0) + 1);
const buckets = Array.from({ length: nums.length + 1 }, () => []);
for (const [value, f] of freq) buckets[f].push(value);
const out = [];
for (let f = buckets.length - 1; f > 0 && out.length < k; f--) {
for (const v of buckets[f]) { out.push(v); if (out.length === k) break; }
}
return out;
}