Problem
Section titled “Problem”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 = 2Output: [1,2]Example 2:
Input: nums = [1], k = 1Output: [1]Example 3:
Input: nums = [1,2,1,2,1,2,3,1,3,2], k = 2Output: [1,2]Constraints:
kis 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 , where n is the array’s size.
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”First count how often each value occurs with a hash map freq. Sorting the distinct values by count would give the answer in , which the follow-up rules out. A heap of size k gives ; 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.
Algorithm
Section titled “Algorithm”- Build
freq[x]= number of occurrences ofxinnums. - Create
n + 1empty buckets; for each(x, f)infreq, appendxtobuckets[f]. - For
ffromndown to1, append the values ofbuckets[f]toans, stopping as soon asansholdskvalues. - Return
ans.
Walkthrough
Section titled “Walkthrough”Example 3, nums = [1,2,1,2,1,2,3,1,3,2], k = 2:
| step | state |
|---|---|
| count | freq = {1: 4, 2: 4, 3: 2} |
| bucket | buckets[4] = [1, 2], buckets[2] = [3], all others empty |
scan from f = 10 down | buckets 10 to 5 are empty; buckets[4] gives 1 and 2; ans has k = 2 values, stop |
Result: [1, 2].
Complexity
Section titled “Complexity”- Time: — counting is one pass with average hash operations, filling the buckets touches each distinct value once, and the scan visits at most
n + 1buckets. - Space: — the hash map and the buckets each hold at most
nentries.
Edge cases
Section titled “Edge cases”- All values distinct: every value lands in
buckets[1]. Since the answer must be unique,kthen 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 ansGive it a try first
Attempt the problem on LeetCode — the code will still be here.