# Program to find second most frequent character

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.
Implementation:

## C++

 `#include ` `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 code ` `int` `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`

## C

 `#include ` `#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 function` `int` `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

 `// Java Program to find the second ` `// most frequent character in a given string` `public` `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

 `# 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 code` `if` `__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#

 `// C# Program to find the second most frequent` `// character in a given string` `using` `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.`

## Javascript

 ``

## PHP

 ` ``\$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` `?>`

Output

```Second most frequent char is g

```

Time Complexity: O(N), as we are using a loop for traversing the string.
Auxiliary Space: O(256), as we are using extra space for count array.

#### Approach#2: Using counter

This approach code uses the Counter class from the collections module to count the frequencies of each character in the input string. It then creates a list of tuples from the Counter object, sorts it by frequency in descending order, and returns the character with the second highest frequency (if there is one).

#### Algorithm

1. Define the input string.
2. Import the Counter class from the collections module and use it to count the frequencies of each character in the string.
3. Create a list of tuples from the Counter object, with each tuple containing a character and its frequency.
4. Sort the list by frequency in descending order.
5. Return the second element of the list (i.e., the character with the second highest frequency)

## C++

 `#include ` `#include ` `#include `   `// Function to find the second most frequent` `// character` `char` `second_most_frequent_char(std::string s)` `{` `    ``std::map<``char``, ``int``> freqs;` `    ``for` `(``char` `c : s) {` `        ``freqs++;` `    ``}`   `    ``// Lambda Function` `    ``auto` `cmp = [](``const` `std::pair<``char``, ``int``>& a,` `                  ``const` `std::pair<``char``, ``int``>& b) {` `        ``return` `a.second > b.second;` `    ``};` `    ``std::vector > sorted_freqs(` `        ``freqs.begin(), freqs.end());` `    ``std::sort(sorted_freqs.begin(), sorted_freqs.end(),` `              ``cmp);` `    ``return` `sorted_freqs.size() > 1 ? sorted_freqs.first` `                                   ``: ``'\0'``;` `}`   `// Driver Code` `int` `main()` `{` `    ``std::string s = ``"geeksforgeeks"``;` `    ``std::cout << second_most_frequent_char(s) << std::endl;` `    ``return` `0;` `}`

## Python3

 `from` `collections ``import` `Counter`   `def` `second_most_frequent_char(s):` `    ``freqs ``=` `Counter(s)` `    ``sorted_freqs ``=` `sorted``(freqs.items(), key``=``lambda` `x: x[``1``], reverse``=``True``)` `    ``return` `sorted_freqs[``1``][``0``] ``if` `len``(sorted_freqs) > ``1` `else` `None` `s``=``"geeksforgeeks"` `print``(second_most_frequent_char(s))`

## C#

 `using` `System;` `using` `System.Collections.Generic;` `using` `System.Linq;`   `class` `Program` `{` `    ``// Define a function to find the second most frequent character in a string` `    ``static` `char``? SecondMostFrequentChar(``string` `s)` `    ``{` `        ``// Create a dictionary to store character frequencies` `        ``Dictionary<``char``, ``int``> freqs = ``new` `Dictionary<``char``, ``int``>();`   `        ``// Count the frequency of each character in the input string` `        ``foreach` `(``char` `c ``in` `s)` `        ``{` `            ``if` `(freqs.ContainsKey(c))` `            ``{` `                ``freqs++;` `            ``}` `            ``else` `            ``{` `                ``freqs = 1;` `            ``}` `        ``}`   `        ``// Sort the dictionary by frequency in descending order` `        ``var` `sortedFreqs = freqs.OrderByDescending(pair => pair.Value);`   `        ``// Check if there is at least a second most frequent character` `        ``if` `(sortedFreqs.Count() > 1)` `        ``{` `            ``// Return the character with the second highest frequency` `            ``return` `sortedFreqs.ElementAt(1).Key;` `        ``}` `        ``else` `        ``{` `            ``// If there is no second most frequent character, return null` `            ``return` `null``;` `        ``}` `    ``}`   `    ``// Test the function with a sample string` `    ``static` `void` `Main()` `    ``{` `        ``string` `s = ``"geeksforgeeks"``;` `        ``Console.WriteLine(SecondMostFrequentChar(s)); ``// Output: 'g'` `    ``}` `}`

## Javascript

 `// Define a function to find the second most frequent character in a string` `function` `secondMostFrequentChar(s) {` `  ``// Create an empty object to store character frequencies` `  ``const freqs = {};`   `  ``// Count the frequency of each character in the input string` `  ``for` `(const char of s) {` `    ``if` `(freqs[char]) {` `      ``freqs[char]++;` `    ``} ``else` `{` `      ``freqs[char] = 1;` `    ``}` `  ``}`   `  ``// Convert the frequency object into an array of key-value pairs` `  ``const sortedFreqs = Object.entries(freqs);`   `  ``// Sort the key-value pairs based on frequency in descending order` `  ``sortedFreqs.sort((a, b) => b - a);`   `  ``// Check if there is at least a second most frequent character` `  ``if` `(sortedFreqs.length > 1) {` `    ``// Return the character with the second highest frequency` `    ``return` `sortedFreqs;` `  ``} ``else` `{` `    ``// If there is no second most frequent character, return null` `    ``return` `null``;` `  ``}` `}`   `// Test the function with a sample string` `const s = ``"geeksforgeeks"``;` `console.log(secondMostFrequentChar(s)); ``// Output: "g"`

Output

```g

```

Time Complexity:
The time complexity of this program is O(n log n), where n is the length of the input string. This is because we need to sort the list of character frequencies, which takes O(n log n) time using the built-in sorted() function in Python. The other operations in the program take O(n) time.

Space Complexity:
The space complexity of this program is O(n), where n is the number of distinct characters in the input string. This is because we need to store each character and its frequency in the Counter object.

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Previous
Next