Back to problems Solve on LeetCode →

Top K Frequent Elements

LeetCode 347 • Medium • Arrays & Hashing

Given nums and k, return the k most frequent elements. Bucket sort: index = frequency.

TimeO(n)count + bucket collect
SpaceO(n)count + buckets
Bucket i: Result:
Input / Count
Current bucket
Result
Count
Result
Ready
Press Play. Count frequencies with a hash map, build buckets (index = freq), then collect from highest bucket down until we have k elements.