Maximum occurring character in an input string using C++


In this problem, we are given an input string of lowercase characters. Our task is to maximum occurring character in an input string.

In case of multiple values with the same frequency of occurrence, we need to print lexicographically smaller values.

Let’s take an example to understand the problem,

Input

string = “programming”

Output

g

Solution Approach

To find the solution to the problem, we need to sort the read string and then traverse the string so that we could find the character which has maximum occurrence in the string. We would use hashing method (hash table method) to conquer this problem. Traversing and hashing the each individual character into an array of characters is called hashing.

Usually, hash array size is allotted to be 256. But if the string contains only characters ranging from 0 to 127 we may use a hash table of size 128, so that we will be able to deallocate hash table size according to the string.

Algorithm

  • Read an input string.

  • Create a function to calculate the maximum occurring character in the string.

  • Create an array to keep the count of individual characters and initialize the array as 0.

  • Construct character count array from the input string.

  • Initialize max count and result.

  • Traverse through the string and maintain the count of each other.

  • At last, find the character with the maximum count and print it.

Example

Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;
char findMaxOccuringChar(char str[]){
   int freq[26] = { 0 };
   int maxFreq = -1;
   char maxFreqChar;
   int len = strlen(str);
   for (int i = 0; i < len; i++)
      freq[str[i] - 'a']++;
   for (int i = 0; i < 26; i++)
      if (maxFreq < freq[i]) {
         maxFreq = freq[i];
         maxFreqChar = (char)(i + 'a');
      }
   return maxFreqChar;
}
int main(){
   char str[] = "programming";
   cout<<"Maximum occurring character of input string is "<<findMaxOccuringChar(str);
   return 0;
}

Output

Maximum occurring character of input string is g

Updated on: 11-Feb-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements