Sort Characters by Frequency

Big-O & the Python Toolkit, problem 4 of 7

Sort Characters by Frequency

Medium

LC #451

hash mapcountingsorting

Not attempted yet

Given a string s, return a string with the same characters, arranged so that characters that occur more often come first. All copies of a character must be next to each other.

Characters with the same count may appear in any order. Upper- and lower-case letters are different characters.

Example 1

Input: s = "tree"
Output: "eetr"

"e" appears twice. "eert" is also accepted.

Example 2

Input: s = "abbccc"
Output: "cccbba"

Example 3

Input: s = "Aabb"
Output: "bbAa"

"bbaA" is also accepted.

Constraints

  • 0 ≤ s.length ≤ 2·10⁵
  • s holds ASCII English letters and digits.

Python

Loading draft…

Test results

8 tests available

No results yet

Run tests your code against the examples; Submit runs the hidden tests too.

3 examples, 5 hidden

Run examples, then submit all tests.