Program to find second most frequent character - GeeksforGeeks

01 Jun, 2021
Given a string, find the second most frequent character in it. Expected time complexity is O(n) where n is the length of the input string.Examples: 
Input: str = "aabababa";
Output: Second most frequent character is 'b'

Input: str = "geeksforgeeks";
Output: Second most frequent character is 'g'

Input: str = "geeksquiz";
Output: Second most frequent character is 'g'
The output can also be any other character with 
count 1 like 'z', 'i'.

Input: str = "abcd";
Output: No Second most frequent character
A simple solution is to start from the first character, count its occurrences, then second character, and so on. While counting these occurrences keep track of max and second max. Time complexity of this solution is O(n2). We can solve this problem in O(n) time using a count array with a size equal to 256 (Assuming characters are stored in ASCII format). Following is the implementation of the approach.  
C++
C
Java
Python 3
C#
PHP
Javascript
#include <bits/stdc++.h>using namespace std;#define NO_OF_CHARS 256 // CPP function to find the// second most frequent character// in a given string 'str'char getSecondMostFreq(string str){    // count number of occurrences of every character.    int count[NO_OF_CHARS] = {0}, i;    for (i = 0; str[i]; i++)        (count[str[i]])++;     // Traverse through the count[] and    // find second highest element.    int first = 0, second = 0;    for (i = 0; i < NO_OF_CHARS; i++)    {        /* If current element is smaller        than first then update both        first and second */        if (count[i] > count[first])        {            second = first;            first = i;        }         /* If count[i] is in between first        and second then update second */        else if (count[i] > count[second] &&                count[i] != count[first])            second = i;    }     return second;} // Driver codeint main(){    string str = "geeksforgeeks";    char res = getSecondMostFreq(str);    if (res != '\0')        cout << "Second most frequent char is " << res;    else        cout << "No second most frequent character";    return 0;} // This code is contributed by rathbhupendra
#include <stdio.h>#define NO_OF_CHARS 256 // C function to find the second most frequent character// in a given string 'str'char getSecondMostFreq(char *str){    // count number of occurrences of every character.    int count[NO_OF_CHARS] = {0}, i;    for (i=0; str[i]; i++)        (count[str[i]])++;     // Traverse through the count[] and find second highest element.    int first = 0, second = 0;    for (i = 0; i < NO_OF_CHARS; i++)    {        /* If current element is smaller than first then update both          first and second */        if (count[i] > count[first])        {            second = first;            first = i;        }         /* If count[i] is in between first and second then update second  */        else if (count[i] > count[second] &&                 count[i] != count[first])            second = i;    }     return second;} // Driver program to test above functionint main(){  char str[] = "geeksforgeeks";  char res = getSecondMostFreq(str);  if (res != '\0')     printf("Second most frequent char is %c", res);  else     printf("No second most frequent character");  return 0;}
// Java Program to find the second// most frequent character in a given stringpublic class GFG{    static final int NO_OF_CHARS = 256;         // finds the second most frequently occurring    // char    static char getSecondMostFreq(String str)    {        // count number of occurrences of every        // character.        int[] count = new int[NO_OF_CHARS];        int i;        for (i=0; i< str.length(); i++)            (count[str.charAt(i)])++;              // Traverse through the count[] and find        // second highest element.        int first = 0, second = 0;        for (i = 0; i < NO_OF_CHARS; i++)        {            /* If current element is smaller than            first then update both first and second */            if (count[i] > count[first])            {                second = first;                first = i;            }                  /* If count[i] is in between first and            second then update second  */            else if (count[i] > count[second] &&                     count[i] != count[first])                second = i;        }              return (char)second;    }          // Driver program to test above function    public static void main(String args[])    {      String str = "geeksforgeeks";      char res = getSecondMostFreq(str);      if (res != '\0')         System.out.println("Second most frequent char"+                                       " is " + res);      else         System.out.println("No second most frequent"+                                       "character");    }}// This code is contributed by Sumit Ghosh
# Python 3 Program to find the# second most frequent character# in a given string # Function to find the second# most frequent character# in a given string 'str'def getSecondMostFreq(str) :     NO_OF_CHARS = 256     # Initialize count list of    # 256 size with value 0    count = [0] * NO_OF_CHARS     # count number of occurrences    # of every character.    for i in range(len(str)) :        count[ord(str[i])] += 1     first, second = 0, 0     # Traverse through the count[]    # and find second highest element.    for i in range(NO_OF_CHARS) :         # If current element is smaller        # than first then update both        # first and second        if count[i] > count[first] :             second = first            first = i         # If count[i] is in between        # first and second        # then update second */        elif (count[i] > count[second] and            count[i] != count[first] ) :                         second = i     # return character    return chr(second) # Driver codeif __name__ == "__main__" :     str = "geeksforgeeks"         # function calling    res = getSecondMostFreq(str)    if res != '\0' :        print("Second most frequent char is", res)    else :        print("No second most frequent character") # This code is contributed by ANKITRAI1
// C# Program to find the second most frequent// character in a given stringusing System; public class GFG {         static int NO_OF_CHARS = 256;         // finds the second most frequently    // occurring char    static char getSecondMostFreq(string str)    {                 // count number of occurrences of every        // character.        int []count = new int[NO_OF_CHARS];         for (int i = 0; i < str.Length; i++)            (count[str[i]])++;             // Traverse through the count[] and find        // second highest element.        int first = 0, second = 0;                 for (int i = 0; i < NO_OF_CHARS; i++)        {                         /* If current element is smaller            than first then update both first            and second */            if (count[i] > count[first])            {                second = first;                first = i;            }                 /* If count[i] is in between first            and second then update second */            else if (count[i] > count[second] &&                       count[i] != count[first])                second = i;        }             return (char)second;    }         // Driver program to test above function    public static void Main()    {        string str = "geeksforgeeks";        char res = getSecondMostFreq(str);                 if (res != '\0')            Console.Write("Second most frequent char"+                                        " is " + res);        else            Console.Write("No second most frequent"+                                        "character");    }} // This code is contributed by nitin mittal.
<?php$NO_OF_CHARS=256; // PHP function to find the// second most frequent character// in a given string 'str'function getSecondMostFreq($str){    global $NO_OF_CHARS;         // count number of occurrences of every character.    $count=array_fill(0,$NO_OF_CHARS,0);    for ($i = 0; $i < strlen($str); $i++)        $count[ord($str[$i])]++;     // Traverse through the count[] and    // find second highest element.    $first = $second = 0;    for ($i = 0; $i < $NO_OF_CHARS; $i++)    {        /* If current element is smaller        than first then update both        first and second */        if ($count[$i] > $count[$first])        {            $second = $first;            $first = $i;        }         /* If count[i] is in between first        and second then update second */        else if ($count[$i] > $count[$second] &&                $count[$i] != $count[$first])            $second = $i;    }     return chr($second);}     // Driver code    $str = "geeksforgeeks";    $res = getSecondMostFreq($str);    if (strlen($res))        echo "Second most frequent char is ".$res;    else        echo "No second most frequent character"; // This code is contributed by mits?>
<script>     // JavaScript Program to find    // the second most frequent    // character in a given string         let NO_OF_CHARS = 256;           // finds the second most frequently    // occurring char    function getSecondMostFreq(str)    {                   // count number of occurrences of every        // character.        let count = new Array(NO_OF_CHARS);        count.fill(0);           for (let i = 0; i < str.length; i++)            (count[str[i].charCodeAt()])++;               // Traverse through the count[] and find        // second highest element.        let first = 0, second = 0;                   for (let i = 0; i < NO_OF_CHARS; i++)        {                           /* If current element is smaller            than first then update both first            and second */            if (count[i] > count[first])            {                second = first;                first = i;            }                   /* If count[i] is in between first            and second then update second */            else if (count[i] > count[second] &&                       count[i] != count[first])                second = i;        }               return String.fromCharCode(second);    }         let str = "geeksforgeeks";    let res = getSecondMostFreq(str);     if (res != '\0')      document.write("Second most frequent char"+                    " is " + res);    else      document.write("No second most frequent"+                    "character");     </script>
Output: 
Second most frequent char is g
 
YouTubeGeeksforGeeks507K subscribersFind second most frequent character in a string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:53•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=KK5M4GLsuAg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
nitin mittal
ankthon
rathbhupendra
Mithun Kumar
divyeshrabadiya07
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews