Ctrl K

Characters Grouped by Count

Medium
A typesetter sorts the characters of the string text into piles: equal characters must stand next to each other, and the piles go from the largest to the smallest (a pile's size is how many times its character occurs in text). If two piles have the same size, the one whose character appears earlier in text goes first. Uppercase and lowercase letters count as different characters. Return the resulting string.
Example 1
text="banana" → 'aaannb'

a occurs 3 times, n twice and b once, so the answer is "aaannb".

Example 2
text="xyz1y" → 'yyxz1'

yy comes first. The other characters occur once each, so they follow in order of first appearance: x, z, 1.

Example 3
text="Mm" → 'Mm'

M and m are different characters, one each; M shows up first.

Constraints
  • 1 ≤ len(text) ≤ 5·10⁵
  • text consists of English letters (upper and lower case) and digits
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsMost Searched Words MediumMost Common Values MediumNo Twin Letters Side by Side MediumFill the Blanks With the Fewest Repeats MediumEqual Letters Kept Apart Hard
loading Python…
Input
text="banana"
Expected
'aaannb'

Run checks the first 3 tests in your browser. Submit checks all 52 tests on the server, hidden ones included.