File tree 1 file changed +8
-7
lines changed
scripts/algorithms/R/Reorganize String 1 file changed +8
-7
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 94 ms (Top 77.32%) | Memory: 44.2 MB (Top 71.88%)
1
2
var reorganizeString = function ( s ) {
2
3
const charMap = { } ;
3
4
const res = [ ] ;
4
-
5
+
5
6
// Store the count of each char
6
7
for ( let char of s ) {
7
8
charMap [ char ] = ( charMap [ char ] || 0 ) + 1 ;
8
9
}
9
-
10
+
10
11
// Sort in descending order by count
11
12
const sortedMap = Object . entries ( charMap ) . sort ( ( a , b ) => b [ 1 ] - a [ 1 ] ) ;
12
-
13
+
13
14
// Check if we can distribute the first char by every other position.
14
15
// We only need to check the first char b/c the chars are ordered by count
15
16
// so if the first char succeeds, all following chars will succeed
16
17
if ( sortedMap [ 0 ] [ 1 ] > Math . floor ( ( s . length + 1 ) / 2 ) ) return '' ;
17
-
18
+
18
19
let position = 0 ;
19
20
for ( let entry of sortedMap ) {
20
21
const char = entry [ 0 ]
@@ -25,12 +26,12 @@ var reorganizeString = function(s) {
25
26
// for placing chars in odd positions
26
27
res [ position ] = char ;
27
28
position += 2 ;
28
-
29
+
29
30
// This will only happen once since total number of chars
30
31
// will be exactly equal to the length of s
31
32
if ( position >= s . length ) position = 1 ;
32
33
}
33
34
}
34
-
35
+
35
36
return res . join ( '' ) ;
36
- } ;
37
+ } ;
You can’t perform that action at this time.
0 commit comments