451. Sort Characters By Frequency

https://leetcode.com/problems/sort-characters-by-frequency/

hashmap + sort O(NlogN)

from collections import Counter
class Solution:
    def frequencySort(self, s: str) -> str:
        c = Counter(s)
        return "".join(sorted(s,key=lambda x:(-c[x],x)))
        

HashMap + bucket sort

from collections import Counter
class Solution:
    def frequencySort(self, s: str) -> str:
        if s=="":
            return ""
        c = Counter(s)
        max_freq = max(c.values())
        buckets = [[] for _ in range(max_freq+1)]
        
        for ch,freq in c.items():
            buckets[freq].append(ch)
        
        res=""
        for i in range(len(buckets)-1,0,-1):
            if len(buckets[i]) > 0:
                for ch in buckets[i]:
                    res+= ch * i
        return res

Last updated

Was this helpful?