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)
- Minimum distance between any most frequent and least frequent element of an array
- Program to find second most frequent character
- Most frequent word in first String which is not present in second String
- Find the most frequent digit without using array/string
- Most frequent element in Array after replacing given index by K for Q queries
- Python - Least Frequent Character in String
- Find top k (or most frequent) numbers in a stream
- Most frequent word in an array of strings
- Smallest subarray with all occurrences of a most frequent element
- Most frequent element in an array
- Queries to insert, delete one occurrence of a number and print the least and most frequent element
- Python | Find most frequent element in a list
- Find k most frequent in linear time
- Queries for rotation and Kth character of the given string in constant time
- Kth character from the Nth string obtained by the given operations
- Swap Kth node from beginning with Kth node from end in a Linked List
- Print Kth character in sorted concatenated substrings of a string
- Program to find the kth character after decrypting a string
- Python | Split string on Kth Occurrence of Character
- Python - Lowercase Kth Character in string
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.