Sort Characters by Frequency

In this tutorial, I am going to discuss a very interesting problem sort characters by frequency.

Given a string, write a method to sort it in decreasing order based on the frequency of characters.

For example:

Example 1

Input : “teee”

Output: “eeet”

Example 2:

  Input: “dddbbb”

Output: “dddbbb”   or “bbbddd” (Both d and b appear 3 times so any of the above output are valid)

  Example 3:

  Input:  “Eett”

Output: “ttEe” or “tteE”  (Both e and E are two different characters so the output should not be “Eett”)