Examples to Understand the Problem

Example 1: Let the given string be “Makeuseof”. The character ’e’ occurs 2 times in the given string and all the other characters occur only once. Thus, the character ’e’ has the highest frequency in the given string.

Example 2: Let the given string be “She sees cheese”. The character ’e’ occurs 6 times in the given string and all the other characters occur less than 6 times. Thus, the character ’e’ has the highest frequency in the given string.

Approach to Find the Most Frequently Occurring Character in a String

The hashing technique is the most efficient way to find the character having the highest frequency in a string. In this technique, the string is traversed and each character of the string is hashed into an array of ASCII characters.

Let the input string be “Makeuseof”, each character of this string is hashed as following:

frequency[‘M’] = 1

frequency[‘a] = 1

frequency[‘k’] = 1

frequency[’e’] = 2

frequency[‘u’] = 1

frequency[’s’] = 1

frequency[‘o’] = 1

frequency[‘f’] = 1

The index of the maximum value in the frequency array is returned. Here 2 is the highest value, therefore ’e’ is returned.

C++ Program to Find the Character With the Highest Frequency

Below is the C++ program to find the character with the highest frequency in a string:

Output:

Python Program to Find the Character With the Highest Frequency

Below is the Python program to find the character with the highest frequency in a string:

Output:

C Program to Find the Character With the Highest Frequency

Below is the C program to find the character with the highest frequency in a string:

Output:

JavaScript Program to Find the Character With the Highest Frequency

Below is the JavaScript program to find the character with the highest frequency in a string:

Output:

Analyze the Time and Space Complexity

The time complexity of the maxFrequencyChar() function is O(n). The space complexity of the maxFrequencyChar() function is O(1) as a fixed space (Hash array). It does not depend on the input string size.

Big-O notation gives you a way to calculate how long it will take to run your code. It’s one of the most important concepts for the analysis of algorithms. If you’re a programmer, you must know about Big-O Notation.