-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path451_sort-characters-by-frequency.js
60 lines (59 loc) · 1.73 KB
/
451_sort-characters-by-frequency.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
*
* Problem:
* Given a string, sort it based on the decreasing frequency of its characters.
* https://leetcode.com/problems/sort-characters-by-frequency/
*
* Example 1:
* Input: "Programming"
* Output: "rrggmmPiano"
* Explanation: 'r', 'g', and 'm' appeared twice, so they need to appear before any
* other character.
*
* Example 2:
* Input: "abcbab"
* Output: "bbbaac"
* Explanation: 'b' appeared three times, 'a' appeared twice, and 'c' appeared only once.
*
* Note: this problem is similar as 347_top-k-frequent-elements, we can treat this
* problem as "top n frequent elements" and use the same strategy to solve it. However,
* we will try to use a different solution here to demonstrate how "counting sort" is
* used when solving problems related to "frequency".
*
* Time: O(n)
* Space: O(n)
*
* @param {string} str
* @return {string}
*/
function sortCharactersByFrequency(str) {
const freqMap = {};
// O(n)
for (let i = 0; i < str.length; i++) {
freqMap[str[i]] = (freqMap[str[i]] || 0) + 1;
}
const buckets = new Array(str.length + 1);
// O(m): m is the unique character count
Object.keys(freqMap).forEach((char) => {
if (!buckets[freqMap[char]]) {
buckets[freqMap[char]] = [];
}
buckets[freqMap[char]].push(char);
});
const result = [];
/**
* loop inside loop, but the total time complexity is O(n), cause each character
* will only be pushed once.
*/
for (let i = str.length; i > 0; i--) {
if (buckets[i]) {
buckets[i].forEach((char) => {
result.push(char.repeat(i));
});
}
}
return result.join('');
}
// Test
console.log(sortCharactersByFrequency('Programming')); // 'rrggmmPoain'
console.log(sortCharactersByFrequency('abcbab')); // 'bbbaac'