C++ Program to Find Most Frequent Character
int freq[256] = {0}; for (char c : str) freq[(unsigned char)c]++; then find max frequency character.Examples
How to Think About It
Algorithm
Code
#include <iostream> #include <string> using namespace std; int main() { string str; getline(cin, str); int freq[256] = {0}; for (char c : str) { freq[(unsigned char)c]++; } int maxFreq = 0; char maxChar = '\0'; for (int i = 0; i < 256; i++) { if (freq[i] > maxFreq) { maxFreq = freq[i]; maxChar = (char)i; } } cout << "Most frequent character: " << maxChar << endl; return 0; }
Dry Run
Let's trace the input 'hello' through the code
Initialize frequency array
freq array all zeros
Count characters
h: freq[104] = 1, e: freq[101] = 1, l: freq[108] = 2, o: freq[111] = 1
Find max frequency
maxFreq = 2, maxChar = 'l'
Print result
Output: Most frequent character: l
| Character | ASCII | Frequency |
|---|---|---|
| h | 104 | 1 |
| e | 101 | 1 |
| l | 108 | 2 |
| o | 111 | 1 |
Why This Works
Step 1: Counting characters
We use an array indexed by ASCII values to count how many times each character appears.
Step 2: Finding the max
We scan the frequency array to find the character with the highest count.
Step 3: Output
We print the character with the highest frequency as the most frequent character.
Alternative Approaches
#include <iostream> #include <string> #include <map> using namespace std; int main() { string str; getline(cin, str); map<char, int> freq; for (char c : str) { freq[c]++; } char maxChar = '\0'; int maxFreq = 0; for (auto& p : freq) { if (p.second > maxFreq) { maxFreq = p.second; maxChar = p.first; } } cout << "Most frequent character: " << maxChar << endl; return 0; }
#include <iostream> #include <string> #include <unordered_map> using namespace std; int main() { string str; getline(cin, str); unordered_map<char, int> freq; for (char c : str) { freq[c]++; } char maxChar = '\0'; int maxFreq = 0; for (auto& p : freq) { if (p.second > maxFreq) { maxFreq = p.second; maxChar = p.first; } } cout << "Most frequent character: " << maxChar << endl; return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The program loops through the input string once (O(n)) and then loops through a fixed size frequency array (256 elements), which is constant time.
Space Complexity
Uses a fixed size array of 256 integers for frequency counts, so space is O(1) regardless of input size.
Which Approach is Fastest?
Using a fixed size array is fastest for ASCII input; maps add overhead but handle wider character sets.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Array frequency | O(n) | O(1) | ASCII input, fastest |
| std::map | O(n log n) | O(n) | Unicode or unknown chars, ordered keys |
| std::unordered_map | O(n) | O(n) | Unicode or unknown chars, faster average |