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.
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 occurrence 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 size equal to 256 (Assuming characters are stored in ASCII format). Following is the implementation of the approach.
Second most frequent char is g
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Kth most frequent Character in a given String
- Program to find the kth character after decrypting a string
- Find the most frequent digit without using array/string
- Find a string such that every character is lexicographically greater than its immediate next character
- Program to count occurrence of a given character in a string
- Program to build a DFA to accept strings that start and end with same character
- Program to build a DFA that accepts strings starting and ending with different character
- How to find the first and last character of a string in Java
- Find k-th character of decrypted string | Set - 2
- Find last index of a character in a string
- Find the last non repeating character in string
- Find k'th character of decrypted string | Set 1
- Find the Nth occurrence of a character in the given String
- Find one extra character in a string
- Given a string, find its first non-repeating character
- Find the first repeated character in a string
- Find repeated character present first in a string
- Find the first non-repeating character from a stream of characters
- Find the last remaining Character in the Binary String according to the given conditions
- Find first non-repeating character in a given string using Linked List