Start learning free

LESSON 85 OF 314 · HASH TABLE

Top K Frequent Elements in C#: O(n) with Bucket Sort

Practice O(n) Read the full explanation

You get an array of integers nums and an integer k.

Return the k values that show up most often in nums, in any order.

How often a value shows up is its frequency. The tests always have one clear answer. Every value you return shows up more often than every value you leave out.

 

Example 1:

Input: nums = [5,3,5,8,3,5,2], k = 2
Output: [3,5]
Explanation: 5 shows up 3 times.
3 shows up twice.
8 and 2 show up once each.
The top 2 are 5 and 3. [5,3] is just as correct.

Example 2:

Input: nums = [9,9,9,9], k = 1
Output: [9]
Explanation: 9 is the only value.

Example 3:

Input: nums = [-2,6,-2,0,6,-2,6,1], k = 2
Output: [-2,6]
Explanation: -2 and 6 both show up 3 times.
0 and 1 show up once each.
A tie inside the answer is fine.
Only the values left out must show up less often.

 

Constraints:

  • 1 to 100,000 numbers.
  • Each number is from -10,000 to 10,000.
  • k is at least 1 and at most the number of different values in nums.
  • There is only one correct set of k values.

Note:

Your algorithm should run in O(n) time and use O(n) extra space, where n is the length of nums. Sorting the values by their frequency would already take O(n log n).

STEP 1 OF 13
    Ctrl + Enter to check

    C# · HASH TABLE

    Top K Frequent Elements in C#, explained

    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

    1. Create count, a Dictionary<int, int> from each value to the number of times it appears.
    2. Loop over nums with foreach.
    3. Add one to the value's count using count.GetValueOrDefault(num, 0) + 1. For a value seen the first time, GetValueOrDefault gives 0, where count[num] would throw KeyNotFoundException.
    4. Declare buckets as an array of List<int> with nums.Length + 1 places, so that index nums.Length exists.
    5. Give every place its own list. A new array of lists holds null in every slot, and adding to a null list would throw NullReferenceException.
    6. Loop over count.Keys, the distinct values, each once.
    7. Add each value to the bucket for its count: buckets[count[num]].Add(num).
    8. Create result, a List<int>, and start freq at nums.Length, the highest count possible.
    9. Loop while result.Count < k. Add the whole bucket at freq with AddRange, then do freq--.
    10. Return result.ToArray(), which turns the list into the int[] 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 throws KeyNotFoundException. Assigning count[5] = 1 is fine and adds the key. That is why the counting line reads with GetValueOrDefault and then assigns.
    • Arrays of reference types start as null. new List<int>[n] allocates n empty slots, not n lists. The loop that creates a list per slot is required.
    • Dictionary order. Enumerating count.Keys doesn'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.
    • Add versus AddRange. Add appends one element. AddRange appends every element of another collection.
    • ToArray() is a method of List<T>, so it needs no extra using. Standalone files need using System.Collections.Generic; for List and Dictionary.

    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} with k = 1 gives {1}. The only bucket used is buckets[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} with k = 2 has 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.Length places instead of nums.Length + 1, an array where one value fills every position (such as {5, 5, 5}) needs index 3 and throws IndexOutOfRangeException.
    • Forgetting to create the lists. The first Add on a null slot throws NullReferenceException.
    • 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} with k = 2 gives {1, 2}.
    • {1} with k = 1 gives {1}.
    • {4, -1, 4, -1, 7, 4, -1, 9} with k = 2 gives {4, -1}.
    • {5, 3, 5, 3, 5, 8} with k = 1 gives {5}.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free