Start learning free

LESSON 228 OF 289 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Most Frequent Element in C#: Count, Then Pick the Winner

Practice Read the full explanation

Given an array of integers nums, return the value that appears in it the most times.

If several values tie for the most appearances, return the one that shows up first in nums. nums has at least one number.

Example 1:

Input: nums = [1, 3, 2, 3, 1, 3]
Output: 3
Explanation: 3 appears three times, 1 twice and 2 once.

Example 2:

Input: nums = [5, 2, 2, 5, 9]
Output: 5
Explanation: 5 and 2 both appear twice. 5 shows up first (at index 0, while 2 first shows up at index 1), so the answer is 5.

Example 3:

Input: nums = [7]
Output: 7
Explanation: The only value is also the most frequent one.
STEP 1 OF 8
    Ctrl + Enter to check

    C# · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Most Frequent Element in C#, explained

    Problem overview

    The method MostFrequent receives an int[] named nums and returns the value that appears the most times. If several values tie, it returns the one that shows up first in the array. The array has at least one number.

    For [1, 3, 2, 3, 1, 3] the answer is 3: it appears three times, 1 twice and 2 once. For [5, 2, 2, 5, 9], both 5 and 2 appear twice, and 5 is first in the array, so the answer is 5. For [7] the answer is 7.

    Approach: two passes

    The work splits into two simple passes over the array.

    The first pass counts. A Dictionary<int, int> maps each value to the number of times it appears. A value already in the dictionary gets 1 added, and a new value is written with the tally 1. The check with ContainsKey is needed because reading a missing key throws a KeyNotFoundException.

    The second pass chooses. Start with the first number as the best, then walk through nums again and replace the best whenever a number has a strictly higher count. Walking nums and not the dictionary matters: the loop meets the values in the order they appear in the array, so on a tie the earlier value stays as the best. The strict > is what keeps it there.

    On [5, 2, 2, 5, 9] the counts are 5 with 2, 2 with 2 and 9 with 1. The best starts at 5. The loop sees 5 (not higher than itself), 2 (a tie, not higher), 2, 5 and 9 (lower), so 5 stays.

    The same idea on [1, 3, 2, 3, 1, 3]: after the first pass the counts are 1 with 2, 3 with 3 and 2 with 1. The best starts at 1, which has count 2. The loop reaches 3 (count 3, higher than 2), so 3 becomes the best. Nothing after that has a count above 3, so the answer is 3. The second pass never changes the dictionary. It only reads from it, and that is why one int is enough to remember the winner.

    Step by step

    1. Create an empty Dictionary<int, int> named counts.
    2. Write a foreach loop over nums with an int named num.
    3. If counts.ContainsKey(num), add 1 to counts[num].
    4. Otherwise set counts[num] to 1. It is the first time this value is seen.
    5. Create an int named best and start it at nums[0]. The first number is the answer until a value with a higher count turns up.
    6. Write a second foreach loop over nums, again with num.
    7. Compare counts with counts[num] > counts[best] and make num the new best when it is true. Strictly greater, so a tie keeps the first value.
    8. Return best.

    The solution in C#

    class Solution {
        public int MostFrequent(int[] nums) {
            Dictionary<int, int> counts = new Dictionary<int, int>();
            foreach (int num in nums) {
                if (counts.ContainsKey(num)) {
                    counts[num] += 1;
                } else {
                    counts[num] = 1;
                }
            }
            int best = nums[0];
            foreach (int num in nums) {
                if (counts[num] > counts[best]) {
                    best = num;
                }
            }
            return best;
        }
    }

    Details worth knowing:

    • Inside the second loop, counts[num] and counts[best] are always safe to read, because the first loop added every value of nums.
    • Both loops use a variable named num. That is allowed because each loop variable lives only inside its own loop.
    • The method returns a value from nums, not its count. Don't return counts[best].

    Complexity

    Each pass visits the n numbers once, and each dictionary operation takes constant time on average, so the time is O(n). The dictionary has one entry per distinct value, so the space is O(k) for k distinct values, at most n.

    A slower way to the same answer is to count each value with a nested loop, which takes O(n²) time. Another is to sort a copy of the array and measure runs of equal values, which takes O(n log n) time, but sorting loses the order of first appearance, so settling ties would need extra bookkeeping. The dictionary keeps the counting simple and the tie rule easy to apply.

    Edge cases and common mistakes

    • Ties. With >= in the second loop, the last of the tied values would win, and [5, 2, 2, 5, 9] would give 2. Walking counts.Keys instead of nums would not promise the first-appearance order either.
    • One element. The array [7] never changes best, which is already 7.
    • Negative numbers and zero. They work as keys like any other int.
    • Returning the count. The answer is the value, not how many times it appears.

    Testing

    numsResult
    [1, 3, 2, 3, 1, 3]3
    [5, 2, 2, 5, 9]5
    [7]7

    Try also an array where every value is different, such as [4, 8, 6]. All the counts are 1, no value is ever strictly higher than the best, and the method returns the first number, 4. Each of the first two rows above comes from the tie rule or the count: in the first, 3 wins on count, and in the second, 5 wins because it comes first.

    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