Sort characters by frequency
September 6, 2022
array-and-hashmapProblem URL: Sort characters by frequency
We will first count the characters of the string and sort them by frequency. Then iterate over it, put the character as many time as it appear in the original string, then finally merge it together to get the result.
class Solution:
def frequencySort(self, s: str) -> str:
count = collections.Counter(s).most_common()
elements = [char * cnt for char, cnt in count]
return ''.join(elements)
Time Complexity: O(nlog(n))
Space Complexity: O(n)