-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0767-reorganize-string.js
More file actions
48 lines (41 loc) · 1.26 KB
/
0767-reorganize-string.js
File metadata and controls
48 lines (41 loc) · 1.26 KB
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
/**
* Reorganize String
* Time Complexity: O(N)
* Space Complexity: O(N)
*/
var reorganizeString = function (s) {
const characterFrequencies = new Map();
for (let traverseIndex = 0; traverseIndex < s.length; ++traverseIndex) {
const individualChar = s[traverseIndex];
characterFrequencies.set(
individualChar,
(characterFrequencies.get(individualChar) || 0) + 1,
);
}
const orderedFrequencies = Array.from(characterFrequencies.entries()).sort(
(firstEntry, secondEntry) => secondEntry[1] - firstEntry[1],
);
const highestFrequency = orderedFrequencies[0][1];
const lengthMidpointCeil = Math.ceil(s.length / 2);
if (highestFrequency > lengthMidpointCeil) {
return "";
}
const outputCharacters = new Array(s.length);
let insertPosition = 0;
for (const currentFrequencyTuple of orderedFrequencies) {
const charToPlace = currentFrequencyTuple[0];
const numOccurrences = currentFrequencyTuple[1];
for (
let occurrenceIterator = 0;
occurrenceIterator < numOccurrences;
++occurrenceIterator
) {
outputCharacters[insertPosition] = charToPlace;
insertPosition += 2;
if (insertPosition >= s.length) {
insertPosition = 1;
}
}
}
return outputCharacters.join("");
};