Skip to content
Related Articles

Related Articles

Kth most frequent Character in a given String

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 19 Jun, 2022

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.
Examples: 
 

Input: str = “GeeksforGeeks”, K = 3 
Output:
Explanation: 
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 
Output:
 

 

Approach 
 

Below is the implementation of the above approach.
 

C++




// C++ program to find kth most frequent
// character in a string
#include <bits/stdc++.h>
using namespace std;
 
// Used for sorting by frequency.
bool sortByVal(const pair<char, int>& a,
               const pair<char, int>& b)
{
    return a.second > b.second;
}
 
// function to sort elements by frequency
char sortByFreq(string str, int k)
{
    // Store frequencies of characters
    unordered_map<char, int> m;
    for (int i = 0; i < str.length(); ++i)
        m[str[i]]++;
 
    // Copy map to vector
    vector<pair<char, int> > v;
    copy(m.begin(), m.end(), back_inserter(v));
 
    // Sort the element of array by frequency
    sort(v.begin(), v.end(), sortByVal);
 
    // Find k-th most frequent item. Please note
    // that we need to consider only distinct
    int count = 0;
    for (int i = 0; i < v.size(); i++) {
 
        // Increment count only if frequency is
        // not same as previous
        if (i == 0 || v[i].second != v[i - 1].second)
            count++;
 
        if (count == k)
            return v[i].first;
    }
 
    return -1;
}
 
// Driver program
int main()
{
    string str = "geeksforgeeks";
    int k = 3;
    cout << sortByFreq(str, k);
    return 0;
}

Java




// Java program to find kth most frequent
// character in a string
import java.io.*;
import java.util.*;
 
class imp3 {
    // Used for sorting by frequency.
    static class pair implements Comparable<pair> {
        char ch;
        int freq;
        pair(char ch, int freq)
        {
            this.ch = ch;
            this.freq = freq;
        }
        public int compareTo(pair a)
        {
            return a.freq - this.freq;
        }
    }
 
    // function to sort elements by frequency
    static char sortByFreq(String str, int k)
    {
        // Store frequencies of characters
        HashMap<Character, Integer> m = new HashMap<>();
        for (int i = 0; i < str.length(); ++i) {
            char ch = str.charAt(i);
            int freq = m.getOrDefault(str.charAt(i), 0) + 1;
            m.put(ch, freq);
        }
 
        // Copy map to array
        pair[] v = new pair[m.size()];
        int idx = 0;
        for (Character ch : m.keySet()) {
            v[idx++] = new pair(ch, m.get(ch));
        }
 
        // Sort the element of array by frequency
        Arrays.sort(v);
 
        // Find k-th most frequent item. Please note
        // that we need to consider only distinct
        int count = 0;
        for (int i = 0; i < v.length; i++) {
 
            // Increment count only if frequency is
            // not same as previous
            if (i == 0 || v[i].freq != v[i - 1].freq)
                count++;
 
            if (count == k)
                return v[i].ch;
        }
 
        return '.';
    }
    public static void main(String[] args)
    {
        String str = "geeksforgeeks";
        int k = 3;
        System.out.println(sortByFreq(str, k));
    }
}
 
// This code is contributed by Karandeep1234

Python3




# Python 3 program to find kth most frequent
# character in a string
 
# function to sort elements by frequency
def sortByFreq(s, k):
    # Store frequencies of characters
    m=dict()
    for c in s:
        m=m.get(c,0)+1
 
    # Copy map to vector
    v=list(m.items())
 
    # Sort the element of array by frequency
    v.sort(key=lambda x:x[1],reverse= True)
 
    # Find k-th most frequent item. Please note
    # that we need to consider only distinct
    count = 0
    for i in range(len(v)):
 
        # Increment count only if frequency is
        # not same as previous
        if (i == 0 or v[i][1] != v[i - 1][1]):
            count+=1
 
        if (count == k):
            return v[i][0]
     
 
    return -1
 
 
# Driver program
if __name__ == '__main__':
    s = "geeksforgeeks"
    k = 3
    print(sortByFreq(s, k))

Javascript




<script>
 
// JavaScript program to find kth most frequent
// character in a string
 
// Used for sorting by frequency.
function sortByVal(a,b)
{
    return b[1] - a[1];
}
 
// function to sort elements by frequency
function sortByFreq(str,k)
{
    // Store frequencies of characters
    let m = new Map();
    for (let i = 0; i < str.length; ++i){
        if(m.has(str[i])){
            m.set(str[i],m.get(str[i])+1);
        }
        else m.set(str[i],1);
    }
 
    // Copy map to vector
    let v = [];
    for(let [x,y] of m){
        v.push([x,y]);
    }
 
    // Sort the element of array by frequency
    v.sort(sortByVal);
 
    // Find k-th most frequent item. Please note
    // that we need to consider only distinct
    let count = 0;
    for (let i = 0; i < v.length; i++) {
 
        // Increment count only if frequency is
        // not same as previous
        if (i == 0 || v[i][1] != v[i - 1][1])
            count++;
 
        if (count == k)
            return v[i][0];
    }
 
    return -1;
}
 
// Driver program
 
let str = "geeksforgeeks";
let k = 3;
document.write(sortByFreq(str, k));
 
// This code is contributed by shinjanpatra.
</script>

Output: 

r

 

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)
 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!