347. Top K Frequent Elements
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to find the k most frequent elements in a given array nums. The output can be in any order. A key constraint is that the time complexity of our algorithm must be better than O(n log n). This rules out simple solutions involving sorting the entire frequency map.
Solution
Top K Frequent Elements in Python
import collections
from typing import List
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# Step 1: Count frequencies of each number.
# collections.Counter is a convenient way to do this.
counts = collections.Counter(nums)
# Step 2: Create buckets to group numbers by frequency.
# The index of the bucket represents the frequency.
# The size is len(nums) + 1 because a number can appear at most len(nums) times.
buckets = [[] for _ in range(len(nums) + 1)]
for num, freq in counts.items():
buckets[freq].append(num)
# Step 3: Collect top k frequent elements from buckets.
result = []
# Iterate from the highest possible frequency down to 1.
for i in range(len(buckets) - 1, 0, -1):
# For each frequency, add the numbers to the result.
for num in buckets[i]:
result.append(num)
# If we have collected k elements, return the result.
if len(result) == k:
return result
return result # Should not be reached given problem constraints.
Top K Frequent Elements in Java
class Solution {
public int[] topKFrequent(int[] nums, int k) {
// Step 1: Count frequencies of each number.
Map<Integer, Integer> counts = new HashMap<>();
for (int num : nums) {
counts.put(num, counts.getOrDefault(num, 0) + 1);
}
// Step 2: Create buckets to group numbers by frequency.
// The index of the bucket represents the frequency.
// The size is nums.length + 1 because a number can appear at most nums.length times.
List<Integer>[] buckets = new List[nums.length + 1];
for (int i = 0; i < buckets.length; i++) {
buckets[i] = new ArrayList<>();
}
for (Map.Entry<Integer, Integer> entry : counts.entrySet()) {
int num = entry.getKey();
int freq = entry.getValue();
buckets[freq].add(num);
}
// Step 3: Collect top k frequent elements from buckets.
int[] result = new int[k];
int index = 0;
// Iterate from the highest possible frequency down to 1.
for (int i = buckets.length - 1; i >= 1; i--) {
// For each frequency, add the numbers to the result.
for (int num : buckets[i]) {
result[index++] = num;
// If we have collected k elements, return the result.
if (index == k) {
return result;
}
}
}
return result; // Should not be reached given problem constraints.
}
}
Top K Frequent Elements in C++
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
// Step 1: Count frequencies of each number.
// The keys are numbers and values are their frequencies.
unordered_map<int, int> counts;
for (int num : nums) {
counts[num]++;
}
// Step 2: Create buckets to group numbers by frequency.
// The index of the bucket represents the frequency.
// The size is nums.size() + 1 because a number can appear at most nums.size() times.
vector<vector<int>> buckets(nums.size() + 1);
for (auto const& [num, freq] : counts) {
buckets[freq].push_back(num);
}
// Step 3: Collect top k frequent elements from buckets.
vector<int> result;
// Iterate from the highest possible frequency down to 1.
for (int i = nums.size(); i >= 1; --i) {
// For each frequency, add the numbers to the result.
for (int num : buckets[i]) {
result.push_back(num);
// If we have collected k elements, return the result.
if (result.size() == k) {
return result;
}
}
}
return result; // Should not be reached given problem constraints.
}
};
Top K Frequent Elements in TypeScript
function topKFrequent(nums: number[], k: number): number[] {
// Step 1: Count frequencies of each number.
const counts = new Map<number, number>();
for (const num of nums) {
counts.set(num, (counts.get(num) || 0) + 1);
}
// Step 2: Create buckets to group numbers by frequency.
// The index of the bucket represents the frequency.
// The size is nums.length + 1 because a number can appear at most nums.length times.
const buckets: number[][] = Array.from({ length: nums.length + 1 }, () => []);
for (const [num, freq] of counts.entries()) {
buckets[freq].push(num);
}
// Step 3: Collect top k frequent elements from buckets.
const result: number[] = [];
// Iterate from the highest possible frequency down to 1.
for (let i = buckets.length - 1; i >= 1; i--) {
// For each frequency, add the numbers to the result.
for (const num of buckets[i]) {
result.push(num);
// If we have collected k elements, return the result.
if (result.length === k) {
return result;
}
}
}
return result; // Should not be reached given problem constraints.
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.