Leetcode 451 Sort Characters By Frequency

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

Input: s = "tree"
Output: "eert"
Explanation: 'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
Input: s = "cccaaa"
Output: "aaaccc"
Explanation: Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers.
Note that "cacaca" is incorrect, as the same characters must be together.
  • Get frequence of each letter and push frequence and letter pair into heap. After pushed all frequence and letter pair into heap, then we pop and append the current letter*frequence to result string.
def frequencySort(self, s: str) -> str:
        heap = []
        for v, c in collections.Counter(s).items():
            heapq.heappush(heap,[-c,v])
        res = ""
        while heap:
            c, v = heapq.heappop(heap)
            res += v*-c
        return res