Payments app~20 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-451hashing · sorting
A payments app draws a small badge for each transfer note. The badge is the note's letters rearranged so the letter used most often comes first. All copies of a letter stay together. Letters used equally often go in alphabetical order, and messages use only lowercase letters.
Write sort_letters_by_frequency(text).
text is a string of lowercase letters a to z.Input: text = "tattle"
Output: "tttael"Count the letters, then group them by count from the highest to the lowest. Within a count, go alphabetically.
| Count | Letters with that count | Added to the result |
|---|---|---|
| 3 | t | ttt |
| 1 | a, e, l | ael |
The result is "tttael".
Input: text = "cccaaa"
Output: "aaaccc"Both letters appear 3 times, so the alphabet decides: aaa comes first. The result is "aaaccc".
Input: text = "z"
Output: "z"A single letter stays as it is: "z".
0 ≤ text.length ≤ 100,000 (letters in a note)text uses only the lowercase letters a to z.Counting the letters again for every position costs about n × n steps, which is 10^10 at n = 100,000. Counting once costs n, and no count can be larger than n, so the counts themselves can be sorted by counting.