Today's challenge wasn't that hard to implement but optimizing the solution. There are different ways to solve today's challenge, but all of them weren't optimal solutions.

The challenge title was “Sort Characters By Frequency.” Let me give you some scenarios so that you can understand it better. If you need more description about the challenge, you can find more detail here.

Example 1:

Input: s = "tree"
Output: "eert"
Explanation: 'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'.
Therefore "eetr" is also a valid answer.

Example 2:

Input: s = "cccaaa"
Output: "aaaccc"
Explanation: Both 'c' and 'a' appear three times,
so both "cccaaa" and "aaaccc" are valid answers.
Note that "cacaca" is incorrect, as the same 
characters must be together.

Example 3:

Input: s = "Aabb"
Output: "bbAa"
Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.

The solution

My first intuition was to use the Counter method from the collections module. There was no problem using the Counter method and looping through the counted characters, but it is so slow. Then I tried different mechanisms to optimize it; it didn't work.

After a while, I realized that I could use dictionary comprehension to count the frequencies of characters. The dictionary comprehension method was better than the Counter method indeed.

The Result

Runtime: 62 ms, faster than 74.68% of Python3 online submissions for Print in Order.

Memory Usage: 15.3 MB, less than 80.91% of Python3 online submissions for Print in Order.