
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Second Most Frequent Character in C++
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
#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
Advertisements