C# Program to Find Most Frequent Character
Dictionary and foreach loop in C#.Examples
How to Think About It
Algorithm
Code
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); } }
Dry Run
Let's trace the input "hello" through the code
Initialize dictionary
counts = {}
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}
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
Output result
Print 'l'
| Character | Count |
|---|---|
| h | 1 |
| e | 1 |
| l | 2 |
| o | 1 |
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
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); } }
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); } }
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Dictionary counting | O(n) | O(k) | All characters, Unicode support |
| LINQ grouping | O(n) | O(k) | Concise code, small inputs |
| Array counting | O(n) | O(1) | ASCII characters, performance |