1
var reorganizeString = function (s) {
2
const charMap = {};
3
const res = [];
4

5
// Store the count of each char
6
for (let char of s) {
7
charMap[char] = (charMap[char] || 0) + 1;
8
}
9

10
// Sort in descending order by count
11
const sortedMap = Object.entries(charMap).sort((a, b) => b[1] - a[1]);
12

13
// Check if we can distribute the first char by every other position.
14
// We only need to check the first char b/c the chars are ordered by count
15
// so if the first char succeeds, all following chars will succeed
16
if (sortedMap[0][1] > Math.floor((s.length + 1) / 2)) return "";
17

18
let position = 0;
19
for (let entry of sortedMap) {
20
const char = entry[0];
21
const count = entry[1];
22
for (let j = 0; j < count; j++) {
23
// Distribute the current char every other position. The same char
24
// will never be placed next to each other even on the 2nd loop
25
// for placing chars in odd positions
26
res[position] = char;
27
position += 2;
28

29
// This will only happen once since total number of chars
30
// will be exactly equal to the length of s
31
if (position >= s.length) position = 1;
32
}
33
}
34

35
return res.join("");
36
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0