# Find Most Frequent character of the String

Find Most Frequent character of the String” is a problem of string data structure. Here, we are given a string of length ‘n’ and our task is to find the most frequent character of the string.

If more than one character has same highest frequency, print the one which appears initially.

Example:

```INPUT:
HELPMESTUDYBRO
OUTPUT:
E is most frequent character present in the string```

There might be multiple ways to find most frequent character of the string. Some of them are:

METHOD 1: Brute – force

The simplest solution to find the most frequent character of the string is to count frequency of each character of the string and print the character with highest frequency.

C++ Program to find most frequent character of the string is as follows:

```#include<bits/stdc++.h>
using namespace std;
int main()
{
string str;
/* Scan the String */
cout<<"Enter a string:\n";
getline(cin,str);

/* Initialize basic variables */
int max = 0;
char res;
int size = str.length();
for(int i = 0; i < size; i++)
{
int count = 0;
/* counting frequency of each character */
for(int j = 0; j < size; j++)
{
if(str[j] == str[i])
{
count++;
}
}
if(count >  max)
{
max = count;
res = str[i];
}
}
cout<<"The most frequent character of the string is "<<res;
}

```
```OUTPUT:
Enter a string:
helpmestudybro
The most frequent character of the string is e
Time Complexity:
O(n^2), where n is the length of the string.```

METHOD 2: Based on Hashing

The steps required to find most frequent character of the string are as follows:

1. Create an array of size 256 and initialize with 0. (we have a character set of 256 characters ;ASCII: 0-255, we create a hash to store the frequency of each character. Initially, each character has 0 frequency).
2. Scan the string and increment array[str[i]] with 1.
3. Finally, scan the array and find the maximum value present in the array and store the index value at local variable. Print the character with ascii value to that of local variable.

C++ Program to find most frequent character of the string is as follows:

```#include<bits/stdc++.h>
using namespace std;
int main()
{
string str;
/* Scan the String */
cout<<"Enter a string:\n";
getline(cin,str);

/* Create a HashMap */
int hash = {0};

/* Scan the string and count frequency
of each character of the string */
for(int i = 0; i < str.length(); i++)
{
hash[str[i]]++;
}

int res = 0;
char ch;

/* Find the most
frequent character */
for(int i = 0; i <  str.length(); i++)
{
if(hash[str[i]] > res)
{
res = hash[str[i]];
ch = str[i];
}
}

/* Print the result */
cout<<"The most frequent character of the string is "<<ch;

}

```
```OUTPUT:
Enter a string:
helpmestudybro
The most frequent character of the string is e
Time Complexity:
O(n), where n is the length of the string.```

Related Posts: