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
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Return maximum occurring character in an input string
- A Program to check if strings are rotations of each other or not
- Write a program to print all permutations of a given string
- Given a string, find its first non-repeating character
- Write a program to reverse an array or string
- Find the smallest window in a string containing all characters of another string
- Given a number, find the next smallest palindrome
- Program to validate an IP address
- Find if a string is interleaved of two other strings | DP-33
- Find the first non-repeating character from a stream of characters
- Find Excel column name from a given column number
- Given a sorted dictionary of an alien language, find order of characters
- Find if an array of strings can be chained to form a circle | Set 1
- Given two strings, find if first string is a subsequence of second
- Find if a given string can be represented from a substring by iterating the substring “n” times
- Find all distinct palindromic sub-strings of a given string
- Find maximum depth of nested parenthesis in a string
- Function to find Number of customers who could not get a computer
- Find the longest substring with k unique characters in a given string
- Find the maximum subarray XOR in a given array