Problem overview
The method TopKFrequent receives an int[] called nums and an integer k, and returns the k values that appear most often in nums, as an int[] in any order. The answer is guaranteed to be unique: every value in it appears more times than every value left out, so there is no tie at the cut. The method should run in O(n) time and use O(n) extra space.
For nums = {1, 1, 1, 2, 2, 3} and k = 2, the value 1 appears three times, 2 appears twice and 3 once, so the answer is {1, 2}. For {4, -1, 4, -1, 7, 4, -1, 9} with k = 2, the values 4 and -1 appear three times each and the others once, so the answer is {4, -1} (or the same two in the other order).
Approach: count, then bucket by count
The first step is always to count how many times each value appears, which a dictionary does in one pass. The question is how to pick the k largest counts. Sorting the distinct values by count costs O(n log n). A min-heap of size k costs O(n log k). Both are good, but the lesson asks for O(n).
The key observation is that a count can never exceed nums.Length. So instead of comparing counts, put each value in a bucket numbered by its count: buckets[f] holds the values that appear exactly f times. This is a bucket sort, and placing a value costs constant time, because the count is directly the index.
The most frequent values then sit in the highest buckets. Start at the top bucket, nums.Length, and walk down, collecting values until you have k of them. Most buckets are empty, but there are only n + 1 of them, so the walk is O(n).
Because the answer is unique, the walk never overshoots: a bucket that carried the result past k values would mean two values with the same count straddling the cut.
Step by step
- Create
count, aDictionary<int, int>from each value to the number of times it appears. - Loop over
numswithforeach. - Add one to the value's count using
count.GetValueOrDefault(num, 0) + 1. For a value seen the first time,GetValueOrDefaultgives 0, wherecount[num]would throwKeyNotFoundException. - Declare
bucketsas an array ofList<int>withnums.Length + 1places, so that indexnums.Lengthexists. - Give every place its own list. A new array of lists holds
nullin every slot, and adding to anulllist would throwNullReferenceException. - Loop over
count.Keys, the distinct values, each once. - Add each value to the bucket for its count:
buckets[count[num]].Add(num). - Create
result, aList<int>, and startfreqatnums.Length, the highest count possible. - Loop while
result.Count < k. Add the whole bucket atfreqwithAddRange, then dofreq--. - Return
result.ToArray(), which turns the list into theint[]the method must return.
The solution in C#
class Solution {
public int[] TopKFrequent(int[] nums, int k) {
Dictionary<int, int> count = new Dictionary<int, int>();
foreach (int num in nums) {
count[num] = count.GetValueOrDefault(num, 0) + 1;
}
List<int>[] buckets = new List<int>[nums.Length + 1];
for (int i = 0; i <= nums.Length; i++) buckets[i] = new List<int>();
foreach (int num in count.Keys) {
buckets[count[num]].Add(num);
}
List<int> result = new List<int>();
int freq = nums.Length;
while (result.Count < k) {
result.AddRange(buckets[freq]);
freq--;
}
return result.ToArray();
}
}
C# details worth knowing:
- Missing keys throw. Reading
count[5]on a dictionary that has no key 5 throwsKeyNotFoundException. Assigningcount[5] = 1is fine and adds the key. That is why the counting line reads withGetValueOrDefaultand then assigns. - Arrays of reference types start as
null.new List<int>[n]allocatesnempty slots, notnlists. The loop that creates a list per slot is required. - Dictionary order. Enumerating
count.Keysdoesn't promise any particular order, which is fine here because the answer may come in any order. If a test compares exact order, sort the result first. AddversusAddRange.Addappends one element.AddRangeappends every element of another collection.ToArray()is a method ofList<T>, so it needs no extrausing. Standalone files needusing System.Collections.Generic;forListandDictionary.
Complexity
Time: O(n). Counting is one pass with constant-time dictionary operations on average. Creating the buckets and filling them takes O(n), since there are at most n distinct values. The downward walk visits at most n buckets and adds each value once.
Space: O(n). The dictionary, the n + 1 buckets and the result all hold at most O(n) items.
Edge cases and common mistakes
- One element.
{1}withk = 1gives{1}. The only bucket used isbuckets[1]. - Negative values. They are fine as dictionary keys. Counts, not values, index the buckets, so negative values cause no index problem.
- Ties above the cut.
{4, -1, 4, -1, 7, 4, -1, 9}withk = 2has two values with count 3. They sit in the same bucket and are both taken together, which is exactly what is needed. - Bucket array too small. With
nums.Lengthplaces instead ofnums.Length + 1, an array where one value fills every position (such as{5, 5, 5}) needs index 3 and throwsIndexOutOfRangeException. - Forgetting to create the lists. The first
Addon anullslot throwsNullReferenceException. - Using
count[num]++to count. It throws on the first occurrence of each value, because the key doesn't exist yet.
Testing
{1, 1, 1, 2, 2, 3}withk = 2gives{1, 2}.{1}withk = 1gives{1}.{4, -1, 4, -1, 7, 4, -1, 9}withk = 2gives{4, -1}.{5, 3, 5, 3, 5, 8}withk = 1gives{5}.
