Frequency Sort String
Given a string s, sort it in decreasing order based on the frequency of the characters. For example, if 'a' appears 3 times and 'b' appears 2 times, all 'a's should come before all 'b's. If two characters have the same frequency, their relative order can be arbitrary, but all occurrences of a character must remain grouped together. The sorting should be case-sensitive.
[ "tree" ]
Explanation. The character 'e' appears twice, while 'r' and 't' appear once. Therefore, 'e' must come before 'r' and 't'. "eert" is one valid answer; "eetr" would also be valid.
[ "cccaaa" ]
Explanation. Both 'c' and 'a' appear three times. Since they have the same frequency, their relative order is arbitrary. "aaaccc" is valid; "cccaaa" would also be valid.
[ "Aabb" ]
Explanation. The character 'b' appears twice, while 'A' and 'a' appear once. 'b' must come first. The order of 'A' and 'a' is arbitrary. "bbAa" is valid; "bbaA" would also be valid.
[ "Panda" ]
Explanation. Character 'a' appears twice, while 'P', 'n', and 'd' each appear once. Thus, all 'a's must come first. The relative order of 'P', 'n', 'd' is arbitrary. "aaPdn" is one valid answer.
[ "abacaba" ]
Explanation. Character frequencies are: 'a': 4, 'b': 2, 'c': 1. The sorted string should place all 'a's first, then all 'b's, then all 'c's.
[ "112233" ]
Explanation. Characters '1', '2', '3' all appear twice. Their relative order is arbitrary. "112233" is a valid output.
Follow-up: Can you solve this problem without directly using a built-in sorting function that accepts a custom comparator, but rather by grouping characters based on their frequencies into 'buckets'?
- `s` consists of uppercase and lowercase English letters and digits. - `1 <= s.length <= 5 * 10^5`
- Views
- 2