Top K Frequent Elements
Medium
Topics
Given an integer array nums and an integer k, return the k most frequent elements. On this judge the answer is returned sorted in ascending order, and the inputs guarantee the k most frequent elements are unambiguous.
Example 1
nums
counts
top 2 by frequency
The distinct values are ranked by how often they occur, and the 2 most frequent are returned — the values themselves, not their counts. Any order among them is accepted, so the answer here is
[1, 2] in some order.Top row is the input; chips are the distinct values with their counts.
Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2]
Example 2
nums
counts
top 1 by frequency
Input: nums = [1], k = 1 Output: [1]
Constraints
- 1 <= nums.length <= 10^5
- k is in the range [1, number of distinct elements]
- The k most frequent elements are unique.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Count frequencies, then you need the k largest by count. A full sort is O(n log n); a bucket indexed by frequency (which is at most n) gets you there in O(n).
Approach
- Count each value’s frequency in a hash map.
- Place values into buckets indexed by their frequency.
- Walk buckets from high frequency down, collecting until you have k values.
Dry Run
nums = [1, 1, 1, 2, 2, 3] k = 2
counts {1: 3, 2: 2, 3: 1}
buckets indexed BY FREQUENCY rather than by value:
f=0 []
f=1 [3]
f=2 [2]
f=3 [1]
f=4, 5, 6 []
walk down from the highest frequency:
bucket f=3 take 1 r = [1]
bucket f=2 take 2 r = [1, 2] k reached, return
answer 1 2
The bucket array works because frequency is BOUNDED: no value can occur more than
n times, so n + 1 lists cover every possible count and "sort by frequency" becomes
an array index. No two counts are ever compared, which is exactly where the log
factor goes.
The array is deliberately oversized -- f=4, 5 and 6 are empty here and simply
walked past. Sizing it to the largest observed count would save a little memory
and change nothing asymptotically.
One honest caveat, measured rather than assumed: in CPython a heap-based
Counter.most_common(k) is FASTER than this bucket loop -- 0.065s against 0.120s at
n = 400000 with k = 100 -- because nlargest is C and the bucket walk is
interpreted Python. O(n) beats O(n log k) on paper and loses on the clock at these
sizes. Both facts are worth being able to state.Complexity
- Time — O(n): counting and bucket placement are linear; bucket scan is bounded by n.
- Space — O(n): the count map and buckets.
Common Pitfalls
- A heap of size k gives O(n log k) — also fine, but bucket sort avoids the log factor.
- Avoiding the log factor does not always make it faster. Measured in CPython at n = 400000 with k = 100,
Counter.most_common(k)— which isheapq.nlargestunderneath — takes 0.065s against 0.120s for the bucket walk, because one is C and the other is interpreted. State the asymptotics, but do not claim a wall-clock win you have not measured.
Full Solution — all languages
class Solution:
def topKFrequent(self, nums, k):
from collections import Counter
c = Counter(nums)
# bucket by frequency: O(n)
buckets = [[] for _ in range(len(nums) + 1)]
for v, f in c.items():
buckets[f].append(v)
r = []
for f in range(len(buckets) - 1, -1, -1):
for v in buckets[f]:
r.append(v)
if len(r) == k:
return r
return rimport java.util.*;
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer,Integer> c=new HashMap<>();
for(int x:nums)c.merge(x,1,Integer::sum);
List<Integer>[] buckets=new List[nums.length+1];
// bucket by frequency: O(n)
for(int f=0;f<buckets.length;f++) buckets[f]=new ArrayList<>();
for(Map.Entry<Integer,Integer> e:c.entrySet()) buckets[e.getValue()].add(e.getKey());
int[] r=new int[k];
int idx=0;
for(int f=buckets.length-1;f>=0&&idx<k;f--) for(int v:buckets[f]) {
r[idx++]=v;
if(idx==k) break;
}
return r;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> c;
for(int x:nums)c[x]++;
vector<vector<int>> buckets(nums.size()+1);
// bucket by frequency: O(n)
for(auto& kv:c) buckets[kv.second].push_back(kv.first);
vector<int> r;
for(int f=(int)buckets.size()-1;f>=0&&(int)r.size()<k;f--) for(int v:buckets[f]) {
r.push_back(v);
if((int)r.size()==k) break;
}
return r;
}
};/**
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/ var topKFrequent = function(nums, k) {
const c={};
for(const x of nums)c[x]=(c[x]||0)+1;
const buckets=Array.from({length:nums.length+1},()=>[]);
// bucket by frequency: O(n)
for(const key in c) buckets[c[key]].push(Number(key));
const r=[];
for(let f=buckets.length-1;f>=0&&r.length<k;f--) for(const v of buckets[f]) {
r.push(v);
if(r.length===k) break;
}
return r;
};