1. Question

Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.

Return the sorted string. If there are multiple answers, return any of them.

2. Analysis

Example 1:
Input: “tree”
Output: “eert”

2.0 Whole Idea.

Use a Object to store the frequency of every character, then sorted the frequency.
Be careful the key in Object can not be duplicate, useless using the Map and Symbol.

2.1 Put every character in to a Object, the key is a character, the value is the Frequency.

const charFreObj = {
    t: 1,
    r: 1,
    e: 2
}

2.2 Sort the Frequency

let sortedFrequency = [2,1,1]

2.2.1 Remove the duplicated value, Important!!!

sortedFrequency = [2,1]
// Using `Set` data structure is easy to handle this problem. 

2.3 Reverse the key and value of charFreObj got in 2.1. Be careful the duplicated value, so put them in to Arrays.

const freCharObj = {
   1: ['t', 'r'],
   2: ['e']
}

2.4 Combined with the result of 2.3, for loop the result of 2.2.1, get the Final Result.

let result = ''
[2,1].forEach(fre => {
   freCharObj[fre].forEach(char => {
        result += char.repeat(fre);
   })
})

// result = 'eetr'

3. Source Code

https://github.com/Terence-Cheng/Frontend_Blog/blob/main/leetcode/451.sort-characters-by-frequency.ts