Top k frequent elements
Return the k values that occur most often. Count with a dictionary, then drop each value into a bucket by its count.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
Count every value in one pass. A count can only be between 1 and n, so make n + 1 buckets and put each value in buckets[count]. Walking the buckets from the highest count down hands out the most frequent values first, with no sorting.
Code
public static int[] TopKFrequent(int[] a, int k) {
var freq = new Dictionary<int, int>();
foreach (int x in a) freq[x] = freq.GetValueOrDefault(x) + 1;
var buckets = new List<int>[a.Length + 1];
foreach (var (value, count) in freq)
(buckets[count] ??= new List<int>()).Add(value);
var result = new List<int>();
for (int c = a.Length; c > 0 && result.Count < k; c--)
if (buckets[c] != null)
foreach (int v in buckets[c])
if (result.Count < k) result.Add(v);
return result.ToArray();
}static int[] topKFrequent(int[] a, int k) {
Map<Integer, Integer> freq = new HashMap<>();
for (int x : a) freq.merge(x, 1, Integer::sum);
List<Integer>[] buckets = new List[a.length + 1];
for (var e : freq.entrySet()) {
if (buckets[e.getValue()] == null) buckets[e.getValue()] = new ArrayList<>();
buckets[e.getValue()].add(e.getKey());
}
List<Integer> result = new ArrayList<>();
for (int c = a.length; c > 0 && result.size() < k; c--)
if (buckets[c] != null)
for (int v : buckets[c])
if (result.size() < k) result.add(v);
return result.stream().mapToInt(Integer::intValue).toArray();
}vector<int> topKFrequent(const vector<int>& a, int k) {
unordered_map<int, int> freq;
for (int x : a) freq[x]++;
vector<vector<int>> buckets(a.size() + 1);
for (auto& [value, count] : freq)
buckets[count].push_back(value);
vector<int> result;
for (int c = a.size(); c > 0 && (int)result.size() < k; c--)
for (int v : buckets[c])
if ((int)result.size() < k) result.push_back(v);
return result;
}from collections import Counter
def top_k_frequent(a: list[int], k: int) -> list[int]:
freq = Counter()
for x in a: freq[x] += 1
buckets = [[] for _ in range(len(a) + 1)]
for value, count in freq.items():
buckets[count].append(value)
result = []
for c in range(len(a), 0, -1):
for v in buckets[c]:
if len(result) < k: result.append(v)
if len(result) == k: break
return resultTips
- GetValueOrDefault(x) returns 0 for a value not yet in the dictionary, so counting is one line.
- Sorting the counts also works but costs O(d log d); a min-heap of size k costs O(n log k).
- Values with the same count may come out in any order; the problem accepts any order.
In the .NET library
??= creates the bucket list only the first time it is needed. Deconstructing a KeyValuePair in foreach (var (value, count) in freq) works since .NET Core 2.0.