Algorithm/NeetCode

Sort Characters By Frequency

Tony Lim 2024. 11. 26. 10:24
728x90

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

class Solution:
    def frequencySort(self, s: str) -> str:
        count = Counter(s) # char -> cnt
        buckets = defaultdict(list) # frequency -> [char]
        
        for char, cnt in count.items():
            buckets[cnt].append(char)
        
        res = []
        for i in range(len(s), 0, -1):
            for c in buckets[i]:
                res.append(c * i)
        return "".join(res)

bucket sort that have sparse key , but we can skip if key doesn't exist in buckets.

728x90