Algo-Sim › Arrays & Hashing
Top K Frequent Elements
Medium · Arrays & Hashing · step through it in Java, Python and C++ on your own input
Return the k most frequent values in O(n): count with a hash map, then bucket the values by frequency.
Problem
Given an integer array nums and an integer k, return the k values that occur most often. The answer is unique, and it may be returned in any order.
Constraints
- 1 ≤ nums.length ≤ 10⁵
- -10⁴ ≤ nums[i] ≤ 10⁴
- 1 ≤ k ≤ number of distinct values
- Must beat O(n log n): sorting all values is not enough
Edge cases to test
- k equals the number of distinct values
- Every value appears once
- Negative numbers
Follow-up questions
- What if the numbers arrive as a stream?
- Keep the counts in a map and a size-k min-heap of (count, value): O(log k) per update. For bounded memory, a Count-Min sketch approximates the counts.
- Why not just sort by frequency?
- Sorting the distinct values costs O(m log m). Bucket sort by count is O(n), and a size-k heap is O(n log k).
Solution
Java
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> count = new LinkedHashMap<>();
for (int x : nums) {
count.merge(x, 1, Integer::sum);
}
List<List<Integer>> buckets = new ArrayList<>();
for (int f = 0; f <= nums.length; f++) {
buckets.add(new ArrayList<>());
}
for (Map.Entry<Integer, Integer> e : count.entrySet()) {
buckets.get(e.getValue()).add(e.getKey());
}
int[] result = new int[k];
int idx = 0;
for (int f = nums.length; f >= 1 && idx < k; f--) {
for (int x : buckets.get(f)) {
if (idx < k) result[idx++] = x;
}
}
return result;
}Python
def top_k_frequent(nums, k):
count = {}
for x in nums:
count[x] = count.get(x, 0) + 1
buckets = [[] for _ in range(len(nums) + 1)]
for x, f in count.items():
buckets[f].append(x)
result = []
for f in range(len(nums), 0, -1):
if len(result) == k:
break
for x in buckets[f]:
if len(result) < k:
result.append(x)
return resultC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> topKFrequent(vector<int> &nums, int k) {
unordered_map<int, int> count;
vector<int> order;
for (int x : nums) {
if (!count.count(x))
order.push_back(x);
count[x] += 1;
}
vector<vector<int>> buckets = {};
for (int f = 0; f <= int(nums.size()); f++) {
buckets.push_back({});
}
for (int x : order) {
buckets[count[x]].push_back(x);
}
vector<int> result = vector<int>(k);
int idx = 0;
for (int f = int(nums.size()); f >= 1 && idx < k; f--) {
for (int x : buckets[f]) {
if (idx < k)
result[idx++] = x;
}
}
return result;
}
};
More Arrays & Hashing problems
- Contains Duplicate (Easy)
- Valid Anagram (Easy)
- Two Sum (Easy)
- Group Anagrams (Medium)
- Encode and Decode Strings (Medium)
- Product of Array Except Self (Medium)
- Longest Consecutive Sequence (Medium)
- Majority Element (Easy)
- Find All Numbers Disappeared in an Array (Easy)
- First Missing Positive (Hard)
- Range Sum Query - Immutable (Easy)
- Subarray Sum Equals K (Medium)
- Design HashMap (Easy)