Top K Frequent Elements

Return the k most frequent elements via bucket sort by frequency.

Medium
Time O(n) Space O(n)
LeetCode
4 min read
top-k heaps bucket-sort

Problem#

Return the k most frequent elements of nums in any order.

Examples#

  • nums = [1,1,1,2,2,3], k = 2[1, 2]
  • nums = [1], k = 1[1]

Constraints#

  • 1 <= nums.length <= 10^5, 1 <= k <= |distinct|.

Approach#

Min-heap of size k — O(n log k).
Bucket by frequency — O(n). Frequencies are bounded by n, so an array indexed by frequency suffices.

Solution#

Top K Frequent (bucket sort)
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> freq;
for (int x : nums) ++freq[x];
vector<vector<int>> buckets(nums.size() + 1);
for (auto& [v, f] : freq) buckets[f].push_back(v);
vector<int> ans;
for (int f = buckets.size() - 1; f >= 0 && (int)ans.size() < k; --f) {
for (int v : buckets[f]) {
ans.push_back(v);
if ((int)ans.size() == k) break;
}
}
return ans;
}
};

Editorial#

The key observation: frequency ∈ [1, n], so bucketing by frequency gives O(n) total. Walk buckets right-to-left until we’ve collected k items. Beats the heap approach by a log k factor.

Complexity#

  • Time: O(n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.