Given a string s
, sort it in decreasing order based on the frequency of characters, and return the sorted string.
Input: s = "tree"
Output: "eert"
Input: s = "cccaaa"
Output: "aaaccc"
Input: s = "Aabb"
Output: "bbAa"
1 <= s.length <= 5 * 10^5
s
consists of uppercase and lowercase English letters and digits.Counter
from the collections
module to count the frequency of each character in the string.Counter
from collections
.s
.from collections import Counter
def frequencySort(s: str) -> str:
# Step 1: Count the frequency of each character
frequency = Counter(s)
# Step 2: Sort the characters based on their frequency in descending order
sorted_chars = sorted(frequency, key=lambda x: (-frequency[x], x))
# Step 3: Reconstruct the string
result = ''.join([char * frequency[char] for char in sorted_chars])
return result
# Example usage:
print(frequencySort("tree")) # Output: "eert"
print(frequencySort("cccaaa")) # Output: "aaaccc"
print(frequencySort("Aabb")) # Output: "bbAa"
O(n)
where n
is the length of the string.O(m log m)
where m
is the number of unique characters (at most this is 62, for 26 lowercase + 26 uppercase + 10 digits, thus this can be considered O(1)).O(n)
since we concatenate n
characters.Overall, the time complexity is O(n log m + n)
which simplifies to O(n log m)
and can be approximated to O(n)
given that m
is a constant (bounded by 62).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?