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.
- Count of substrings having the most frequent character in the string as first character
- Most frequent word in first String which is not present in second String
- Kth most frequent Character in a given String
- Find the most frequent digit without using array/string
- Most frequent word in an array of strings
- Find the character in first string that is present at minimum index in second string
- Second most repeated word in a sequence
- Second most repeated word in a sequence in Python
- Frequency of smallest character in first sentence less than that of second sentence
- Check if a string can be split into two strings with same number of K-frequent characters
- Find a string such that every character is lexicographically greater than its immediate next character
- Count of strings that can be formed from another string using each character at-most once
- Lexicographically smallest string formed by removing at most one character
- Print the most occurring character in an array of strings
- Lexicographically smaller string by swapping at most one character pair
- Count substrings with each character occurring at most k times
- Longest Common Prefix using Character by Character Matching
- Replace every character of string by character whose ASCII value is K times more than it
- Count substrings that starts with character X and ends with character Y
- Replace every character of a string by a different character