In this Leetcode Sort Characters By Frequency problem solution we have given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.

Return the sorted string. If there are multiple answers, return any of them.

Leetcode Sort Characters By Frequency problem solution


Problem solution in Python.

class Solution:
    def frequencySort(self, s: str) -> str:
        dic=collections.defaultdict(int)
        for st in s:dic[st]+=1
        return ''.join(sorted(s,key=lambda x: (dic[x],ord(x)),reverse=True))



Problem solution in Java.

class Solution {
    public String frequencySort(String s) {
        Map<Character,Integer>map=new TreeMap<>();
        for(char ch:s.toCharArray()){
            map.put(ch,map.getOrDefault(ch,0)+1);
        }
        PriorityQueue<Pair>pq=new PriorityQueue<Pair>((obj1,obj2)->obj2.frequency-obj1.frequency);
        for(Map.Entry<Character,Integer>entry:map.entrySet()){
            pq.add(new Pair(entry.getKey(),entry.getValue()));
        }
        StringBuilder sbil=new StringBuilder();
        while(!pq.isEmpty()){
            Pair obj=pq.poll();
            char c=obj.ch;
            int f=obj.frequency;
            for(int i=0;i<f;i++){
                sbil.append(c+"");
            }
        }
        return sbil.toString();
    }
    class Pair{
        int frequency;
        char ch;
        public Pair(char ch,int frequency){
            this.ch=ch;
            this.frequency=frequency;
        }
    }
}


Problem solution in C++.

string frequencySort(string s) {
    unordered_map<char, int>mp;
    for (auto i : s) {
        mp[i]++;
    }
    priority_queue<pair<int, char>>pt;
    for (auto i : mp) {
        pt.push({ i.second,i.first });
    }
    string ans = "";
    while (!empty(pt)) {
        int val = pt.top().first;
        while (val) {
            ans += pt.top().second;
            val--;
        }
        pt.pop();
    }
    return ans;

}


Problem solution in C.

typedef struct
{
    int count;
    char ch;
}Map;

int cmp(const void * a, const void * b)
{
    return ((Map *)b)->count - ((Map *)a)->count;
}

char * frequencySort(char * s){
    Map node[125] = {0};
    int idx = 0;
    for(int i=0; i<strlen(s); i++)
    {
        node[s[i]].count++;
        node[s[i]].ch = s[i];
    }
    qsort(node, 125, sizeof(Map), cmp);
    char * result = (char *)calloc(strlen(s)+1, sizeof(char));
    for(int i=0; i<125; i++)
    {
        if(node[i].count != 0)
        {
            for(int j=0; j<node[i].count; j++)
                result[idx++] = node[i].ch;
        }
        else break;
    }
    return result;
    
}