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 <bits/stdc++.h>
using namespace std;
#define NO_OF_CHARS 256
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 = "geeksforgeeks" ;
char res = getSecondMostFreq(str);
if (res != '\0' )
cout << "Second most frequent char is " << res;
else
cout << "No second most frequent character" ;
return 0;
}
|
C
#include <stdio.h>
#define NO_OF_CHARS 256
char getSecondMostFreq( char *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()
{
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
public class GFG
{
static final int NO_OF_CHARS = 256 ;
static char getSecondMostFreq(String str)
{
int [] count = new int [NO_OF_CHARS];
int i;
for (i= 0 ; i< str.length(); i++)
(count[str.charAt(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 ( char )second;
}
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" );
}
}
|
Python 3
def getSecondMostFreq( str ) :
NO_OF_CHARS = 256
count = [ 0 ] * NO_OF_CHARS
for i in range ( len ( str )) :
count[ ord ( str [i])] + = 1
first, second = 0 , 0
for i in range (NO_OF_CHARS) :
if count[i] > count[first] :
second = first
first = i
elif (count[i] > count[second] and
count[i] ! = count[first] ) :
second = i
return chr (second)
if __name__ = = "__main__" :
str = "geeksforgeeks"
res = getSecondMostFreq( str )
if res ! = '\0' :
print ( "Second most frequent char is" , res)
else :
print ( "No second most frequent character" )
|
C#
using System;
public class GFG {
static int NO_OF_CHARS = 256;
static char getSecondMostFreq( string str)
{
int []count = new int [NO_OF_CHARS];
for ( int i = 0; i < str.Length; i++)
(count[str[i]])++;
int first = 0, second = 0;
for ( int 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 ( char )second;
}
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" );
}
}
|
Javascript
<script>
let NO_OF_CHARS = 256;
function getSecondMostFreq(str)
{
let count = new Array(NO_OF_CHARS);
count.fill(0);
for (let i = 0; i < str.length; i++)
(count[str[i].charCodeAt()])++;
let first = 0, second = 0;
for (let 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 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>
|
PHP
<?php
$NO_OF_CHARS =256;
function getSecondMostFreq( $str )
{
global $NO_OF_CHARS ;
$count = array_fill (0, $NO_OF_CHARS ,0);
for ( $i = 0; $i < strlen ( $str ); $i ++)
$count [ord( $str [ $i ])]++;
$first = $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 chr ( $second );
}
$str = "geeksforgeeks" ;
$res = getSecondMostFreq( $str );
if ( strlen ( $res ))
echo "Second most frequent char is " . $res ;
else
echo "No second most frequent character" ;
?>
|
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 <algorithm>
#include <iostream>
#include <map>
char second_most_frequent_char(std::string s)
{
std::map< char , int > freqs;
for ( char c : s) {
freqs++;
}
auto cmp = []( const std::pair< char , int >& a,
const std::pair< char , int >& b) {
return a.second > b.second;
};
std::vector<std::pair< char , int > > sorted_freqs(
freqs.begin(), freqs.end());
std::sort(sorted_freqs.begin(), sorted_freqs.end(),
cmp);
return sorted_freqs.size() > 1 ? sorted_freqs[1].first
: '\0' ;
}
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
{
static char ? SecondMostFrequentChar( string s)
{
Dictionary< char , int > freqs = new Dictionary< char , int >();
foreach ( char c in s)
{
if (freqs.ContainsKey(c))
{
freqs++;
}
else
{
freqs = 1;
}
}
var sortedFreqs = freqs.OrderByDescending(pair => pair.Value);
if (sortedFreqs.Count() > 1)
{
return sortedFreqs.ElementAt(1).Key;
}
else
{
return null ;
}
}
static void Main()
{
string s = "geeksforgeeks" ;
Console.WriteLine(SecondMostFrequentChar(s));
}
}
|
Javascript
function secondMostFrequentChar(s) {
const freqs = {};
for (const char of s) {
if (freqs[char]) {
freqs[char]++;
} else {
freqs[char] = 1;
}
}
const sortedFreqs = Object.entries(freqs);
sortedFreqs.sort((a, b) => b[1] - a[1]);
if (sortedFreqs.length > 1) {
return sortedFreqs[1][0];
} else {
return null ;
}
}
const s = "geeksforgeeks" ;
console.log(secondMostFrequentChar(s));
|
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!
Last Updated :
11 Dec, 2023
Like Article
Save Article