Program to find second most frequent character
Last Updated :
20 Dec, 2023
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
// 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 <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 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
<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>
PHP
<?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
?>
OutputSecond 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>
// 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[c]++;
}
// Lambda Function
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';
}
// Driver Code
int main()
{
std::string s = "geeksforgeeks";
std::cout << second_most_frequent_char(s) << std::endl;
return 0;
}
Java
// Java code to implement the above approach
import java.util.*;
public class GFG {
public static char secondMostFrequentChar(String s)
{
Map<Character, Integer> freqs = new HashMap<>();
// Count the frequencies of characters
for (char c : s.toCharArray()) {
freqs.put(c, freqs.getOrDefault(c, 0) + 1);
}
// Sort the frequencies in descending order
List<Map.Entry<Character, Integer> > sortedFreqs
= new ArrayList<>(freqs.entrySet());
Collections.sort(
sortedFreqs,
(a, b) -> b.getValue().compareTo(a.getValue()));
// Check if there is a second most frequent
// character
if (sortedFreqs.size() > 1) {
return sortedFreqs.get(2).getKey();
}
else {
return '\0'; // Return null character if there
// is no second most frequent
// character
}
}
public static void main(String[] args)
{
String s = "geeksforgeeks";
char secondMostFreqChar = secondMostFrequentChar(s);
System.out.println(secondMostFreqChar);
}
}
// This code is contributed by Susobhan Akhuli
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[c]++;
}
else
{
freqs[c] = 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[1] - a[1]);
// 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[1][0];
} 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"
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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem