Leetcode 451 Solution

This article provides solution to leetcode question 451 (sort-characters-by-frequency)

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

Solution

class Solution:
    def frequencySort(self, s: str) -> str:
        m = collections.defaultdict(int)
        arr = []
        for ch in s:
            m[ch] += 1
            arr.append(ch)

        arr.sort(key=lambda x: (-m[x], -ord(x)))

        return "".join(arr)