Program to find second most frequent character in C++

C++Server Side ProgrammingProgramming

In this problem, we are given string str. Our task is to create a Program to find second most frequent character in C++.

Let’s take an example to understand the problem

Input

str = “abaacabcba”

Output

‘b’

Solution Approach

To find the character that is second most frequent in the string. We need to maintain a count array chatCount that is used to store the frequency of each character in the string. And then using the array we will find the character with max and secondMax frequency in the array. And display the second most frequent character.

Program to illustrate the working of our solution

Example

 Live Demo

#include <iostream>
#include <string.h>
using namespace std;
char findSecFreqChar(string str){
   int charFreq[256] = {0};
   for (int i = 0; i < str.length(); i++)
      (charFreq[str[i]])++;
      int maxFreq = charFreq[0], secFreq = charFreq[0];
      for (int i = 0; i < 256; i++){
         if (charFreq[i] > charFreq[maxFreq]){
            secFreq = maxFreq;
            maxFreq = i;
      }
      else if (charFreq[i] > charFreq[secFreq] &&
      charFreq[i] != charFreq[maxFreq])
      secFreq = i;
   }
   return secFreq;
}
int main(){
   string str = "tutorialspoint";
   char secFreqChar = findSecFreqChar(str);
   cout << "Second most frequent character of the string is"<<secFreqChar;
   return 0;
}

Output

Second most frequent character of the string is i
raja
Published on 19-May-2020 15:22:53
Advertisements