Program to find second most frequent character in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find the second most frequent character.

For this we will be provided with a string. Our task is to iterate the string only once and find the second most frequent character in it.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
#define NO_OF_CHARS 256
//finding second most frequent character
char getSecondMostFreq(string str) {
   int count[NO_OF_CHARS] = {0}, i;
   for (i = 0; str[i]; i++)
      (count[str[i]])++;
   int first = 0, second = 0;
   for (i = 0; i < NO_OF_CHARS; i++){
      if (count[i] > count[first]){
         second = first;
         first = i;
      }
      else if (count[i] > count[second] &&
      count[i] != count[first])
      second = i;
   }
   return second;
}
int main(){
   string str = "tutorialspoint";
   char res = getSecondMostFreq(str);
   if (res != '\0')
      cout << "Second most frequent char is " << res;
   else
      cout << "No second most frequent character";
   return 0;
}

Output

Second most frequent char is i
raja
Published on 19-May-2020 15:22:53
Advertisements