Given a string str and an integer K, the task is to find the K-th most frequent character in the string. If there are multiple characters that can account as K-th most frequent character then, print any one of them.
Input: str = “GeeksforGeeks”, K = 3
K = 3, here ‘e’ appears 4 times
& ‘g’, ‘k’, ‘s’ appears 2 times
& ‘o’, ‘f’, ‘r’ appears 1 time.
Any output from ‘o’ (or) ‘f’ (or) ‘r’ will be correct.
Input: str = “trichotillomania”, K = 2
- The idea is to Use the Characters as key in Hashmap and store their occurrences in the string.
- Sort the Hashmap and find the K-th character.
Below is the implementation of the above approach.
Time Complexity: O(NlogN) Please note that this is an upper bound on time complexity. If we consider alphabet size as constant (for example lower case English alphabet size is 26), we can say time complexity as O(N). The vector size would never be more that alphabet size.
Auxiliary Space: O(N)
- Python - Least Frequent Character in String
- Program to find second most frequent character
- Most frequent word in first String which is not present in second String
- Minimum distance between any most frequent and least frequent element of an array
- Find the most frequent digit without using array/string
- Check if a string can be split into two strings with same number of K-frequent characters
- Replace every character of string by character whose ASCII value is K times more than it
- Find a string such that every character is lexicographically greater than its immediate next character
- Modify the string such that every character gets replaced with the next character in the keyboard
- Check if frequency of character in one string is a factor or multiple of frequency of same character in other string
- Map every character of one string to another such that all occurrences are mapped to the same character
- Replace all occurrences of character X with character Y in given string
- Replace every character of a string by a different character
- Lexicographically smallest string formed by appending a character from the first K characters of a given string
- Lexicographically smallest string formed by appending a character from first K characters of a string | Set 2
- Find the character in first string that is present at minimum index in second string
- Convert the string into palindrome string by changing only one character.
- Queries to find the first non-repeating character in the sub-string of a string
- Queries to find the last non-repeating character in the sub-string of a given string
- Change string to a new character set
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.