Skip to content

Top K Frequent Elements

Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order.

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:

Input: nums = [1], k = 1
Output: [1]

Example 3:

Input: nums = [1,2,1,2,1,2,3,1,3,2], k = 2
Output: [1,2]

Constraints:

  • 1≤nums.length≤1051 \le nums.length \le 10^5
  • −104≤nums[i]≤104-10^4 \le nums[i] \le 10^4
  • k is in the range [1, the number of unique elements in the array].
  • It is guaranteed that the answer is unique.

Follow-up: Your algorithm’s time complexity must be better than O(nlog⁡n)O(n \log n), where n is the array’s size.

First count how often each value occurs with a hash map freq. Sorting the distinct values by count would give the answer in O(nlog⁡n)O(n \log n), which the follow-up rules out. A heap of size k gives O(nlog⁡k)O(n \log k); we can do even better.

The trick is that a frequency is an integer between 1 and n. So instead of comparison-sorting by frequency we can bucket the values by it: buckets[f] holds every value that occurs exactly f times. Scanning the buckets from f = n down to 1 visits the values in decreasing order of frequency, and the first k values we meet are the answer. Because the answer is guaranteed to be unique, we never have to break a tie at the boundary.

  1. Build freq[x] = number of occurrences of x in nums.
  2. Create n + 1 empty buckets; for each (x, f) in freq, append x to buckets[f].
  3. For f from n down to 1, append the values of buckets[f] to ans, stopping as soon as ans holds k values.
  4. Return ans.

Example 3, nums = [1,2,1,2,1,2,3,1,3,2], k = 2:

stepstate
countfreq = {1: 4, 2: 4, 3: 2}
bucketbuckets[4] = [1, 2], buckets[2] = [3], all others empty
scan from f = 10 downbuckets 10 to 5 are empty; buckets[4] gives 1 and 2; ans has k = 2 values, stop

Result: [1, 2].

  • Time: O(n)O(n) — counting is one pass with average O(1)O(1) hash operations, filling the buckets touches each distinct value once, and the scan visits at most n + 1 buckets.
  • Space: O(n)O(n) — the hash map and the buckets each hold at most n entries.
  • All values distinct: every value lands in buckets[1]. Since the answer must be unique, k then equals the number of values, and all of them are returned.
  • Single element (Example 2): buckets[1] = [1], returned immediately.
  • Negative values: they are only used as map keys and bucket contents, never as indices.

Think before you peek

Work out an approach on your own first — the explanation will still be here when you want it.

class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> freq;
for (int x : nums) freq[x]++;
// buckets[f] = values that occur exactly f times
vector<vector<int>> buckets(nums.size() + 1);
for (auto& [x, f] : freq) buckets[f].push_back(x);
vector<int> ans;
for (int f = nums.size(); f >= 1 && (int)ans.size() < k; f--) {
for (int x : buckets[f]) {
ans.push_back(x);
if ((int)ans.size() == k) break;
}
}
return ans;
}
};
class Solution {
public int[] topKFrequent(int[] nums, int k) {
HashMap<Integer, Integer> freq = new HashMap<>();
for (int x : nums) freq.merge(x, 1, Integer::sum);
// buckets.get(f) = values that occur exactly f times
List<List<Integer>> buckets = new ArrayList<>(nums.length + 1);
for (int f = 0; f <= nums.length; f++) buckets.add(new ArrayList<>());
for (var e : freq.entrySet()) buckets.get(e.getValue()).add(e.getKey());
int[] ans = new int[k];
int size = 0;
for (int f = nums.length; f >= 1 && size < k; f--) {
for (int x : buckets.get(f)) {
ans[size++] = x;
if (size == k) break;
}
}
return ans;
}
}
from collections import Counter
class Solution:
def topKFrequent(self, nums: list[int], k: int) -> list[int]:
freq = Counter(nums)
# buckets[f] = values that occur exactly f times
buckets = [[] for _ in range(len(nums) + 1)]
for x, f in freq.items():
buckets[f].append(x)
ans = []
for f in range(len(nums), 0, -1):
for x in buckets[f]:
ans.append(x)
if len(ans) == k:
return ans
return ans

Give it a try first

Attempt the problem on LeetCode — the code will still be here.