0
0
CsharpProgramBeginner · 2 min read

C# Program to Find Most Frequent Character

Use a dictionary to count characters and find the one with the highest count using Dictionary and foreach loop in C#.
📋

Examples

Inputhello
Outputl
Inputtestcase
Outpute
Inputaabbcc
Outputa
🧠

How to Think About It

To find the most frequent character, count how many times each character appears by going through the string once. Then, find which character has the highest count by comparing all counts.
📐

Algorithm

1
Get the input string.
2
Create a dictionary to store character counts.
3
Loop through each character in the string and update its count in the dictionary.
4
Find the character with the maximum count in the dictionary.
5
Return or print that character.
💻

Code

csharp
using System;
using System.Collections.Generic;

class Program {
    static void Main() {
        string input = "hello";
        var counts = new Dictionary<char, int>();
        foreach (char c in input) {
            counts[c] = counts.GetValueOrDefault(c, 0) + 1;
        }
        char mostFrequent = ' ';
        int maxCount = 0;
        foreach (var pair in counts) {
            if (pair.Value > maxCount) {
                maxCount = pair.Value;
                mostFrequent = pair.Key;
            }
        }
        Console.WriteLine(mostFrequent);
    }
}
Output
l
🔍

Dry Run

Let's trace the input "hello" through the code

1

Initialize dictionary

counts = {}

2

Count characters

After 'h': counts = {'h': 1} After 'e': counts = {'h': 1, 'e': 1} After 'l': counts = {'h': 1, 'e': 1, 'l': 1} After second 'l': counts = {'h': 1, 'e': 1, 'l': 2} After 'o': counts = {'h': 1, 'e': 1, 'l': 2, 'o': 1}

3

Find max count

maxCount = 0, mostFrequent = ' ' Check 'h': count=1 > 0, update maxCount=1, mostFrequent='h' Check 'e': count=1 == maxCount, no change Check 'l': count=2 > 1, update maxCount=2, mostFrequent='l' Check 'o': count=1 < maxCount, no change

4

Output result

Print 'l'

CharacterCount
h1
e1
l2
o1
💡

Why This Works

Step 1: Counting characters

We use a dictionary to keep track of how many times each character appears by increasing the count every time we see the character.

Step 2: Finding the maximum

We check each character's count and remember the one with the highest count using simple comparison.

Step 3: Output the result

The character with the highest count is printed as the most frequent character.

🔄

Alternative Approaches

LINQ approach
csharp
using System;
using System.Linq;

class Program {
    static void Main() {
        string input = "hello";
        var mostFrequent = input.GroupBy(c => c)
                                .OrderByDescending(g => g.Count())
                                .First().Key;
        Console.WriteLine(mostFrequent);
    }
}
This uses LINQ for concise code but may be less clear for beginners.
Array counting for ASCII
csharp
using System;

class Program {
    static void Main() {
        string input = "hello";
        int[] counts = new int[256];
        foreach (char c in input) {
            counts[c]++;
        }
        int maxCount = 0;
        char mostFrequent = ' ';
        for (int i = 0; i < 256; i++) {
            if (counts[i] > maxCount) {
                maxCount = counts[i];
                mostFrequent = (char)i;
            }
        }
        Console.WriteLine(mostFrequent);
    }
}
Faster for ASCII but uses fixed size array and only works for ASCII characters.

Complexity: O(n) time, O(k) space

Time Complexity

The program loops through the string once (n characters) to count, then loops through the dictionary keys (k unique characters) to find the max, so overall O(n).

Space Complexity

Extra space is used for the dictionary storing counts of unique characters, which is O(k), where k is number of unique characters.

Which Approach is Fastest?

The array counting method is fastest for ASCII input due to direct indexing, but dictionary is more flexible for all Unicode characters.

ApproachTimeSpaceBest For
Dictionary countingO(n)O(k)All characters, Unicode support
LINQ groupingO(n)O(k)Concise code, small inputs
Array countingO(n)O(1)ASCII characters, performance
💡
Use a dictionary to count characters efficiently and find the max count easily.
⚠️
Forgetting to initialize counts or not handling characters not yet in the dictionary causes errors.