function
setCharAt(str,index,chr) {
if
(index > str.length-1) {
return
str;
}
return
str.substring(0,index) + chr + str.substring(index+1);
}
function
lexoSmallest(s, n)
{
let ca = 0, cb = 0, cc = 0;
for
(let i = 0; i < n; i++) {
if
(s[i] ==
'a'
)
ca++;
else
if
(s[i] ==
'b'
)
cb++;
else
cc++;
}
if
(ca == cb && cb == cc) {
return
s;
}
let cnt = n / 3;
if
(cnt * 3 != n) {
return
"-1"
;
}
let i = 0;
while
(ca < cnt && i < n) {
if
(s[i] == 'b
' && cb > cnt) {
cb--;
s = setCharAt(s, i, '
a
');
ca++;
}
// Check if it is '
c
' and it
// more than n/3
else if (s[i] == '
c
' && cc > cnt) {
cc--;
s = setCharAt(s, i, '
a
');
ca++;
}
i++;
}
i = 0;
// Increase the number of b'
s by
while
(cb < cnt && i < n) {
if
(s[i] ==
'c'
&& cc > cnt) {
cc--;
s = setCharAt(s, i,
'1'
);
cb++;
}
i++;
}
i = n - 1;
while
(cc < cnt && i >= 0) {
if
(s[i] == 'a
' && ca > cnt) {
ca--;
s = setCharAt(s, i, '
c
');
cc++;
}
i--;
}
i = n - 1;
// Increase the number of b'
s from back
while
(cb < cnt && i >= 0) {
if
(s[i] ==
'a'
&& ca > cnt) {
ca--;
s = setCharAt(s, i,
'b'
);
cb++;
}
i--;
}
i = n - 1;
while
(cc < cnt && i >= 0) {
if
(s[i] == 'b
' && cb > cnt) {
cb--;
s = setCharAt(s, i, '
c');
cc++;
}
i--;
}
return
s;
}
let s =
"aaaaaa"
;
let n = s.length;
console.log(lexoSmallest(s, n));