const MAX_CHAR = 26;
function
countFreq(str, freq, n)
{
for
(let i = 0; i < n; i++)
freq[str[i].charCodeAt(0) - 97]++;
return
freq;
}
function
canMakePalindrome(freq, n)
{
let count_odd = 0;
for
(let i = 0; i < MAX_CHAR; i++)
if
(freq[i] % 2 != 0)
count_odd++;
if
(n % 2 == 0) {
if
(count_odd > 0)
return
false
;
else
return
true
;
}
if
(count_odd != 1)
return
false
;
return
true
;
}
function
findOddAndRemoveItsFreq(freq)
{
let odd_char =
'#'
;
for
(let i = 0; i < MAX_CHAR; i++) {
if
(freq[i] % 2 != 0) {
freq[i]--;
odd_char = String.fromCharCode(i + 97);
break
;
}
}
return
odd_char;
}
function
findPalindromicString(str, n)
{
let freq =
new
Array(MAX_CHAR).fill(0);
freq = countFreq(str, freq, n);
if
(!canMakePalindrome(freq, n))
return
false
;
let odd_char = findOddAndRemoveItsFreq(freq);
let front_index = 0, rear_index = n - 1;
for
(let i = 0; i < MAX_CHAR; i++) {
if
(freq[i] != 0) {
let ch = String.fromCharCode(i + 97);
for
(let j = 1; j <= Math.floor(freq[i] / 2); j++) {
str[front_index++] = ch;
str[rear_index--] = ch;
}
}
}
if
(front_index == rear_index)
str[front_index] = odd_char;
return
true
;
}
function
swap(a, b){
return
[b, a];
}
function
reverse(str, i, j)
{
while
(i < j) {
[str[i], str[j]] = swap(str[i], str[j]);
i++;
j--;
}
return
str;
}
function
nextPalin(str, n)
{
if
(n <= 3)
return
false
;
let mid = Math.floor(n / 2) - 1;
let i, j;
for
(i = mid - 1; i >= 0; i--)
if
(str[i] < str[i + 1])
break
;
if
(i < 0)
return
false
;
let smallest = i + 1;
for
(j = i + 2; j <= mid; j++)
if
(str[j] > str[i] && str[j] < str[smallest])
smallest = j;
[str[i], str[smallest]] = swap(str[i], str[smallest]);
[str[n - i - 1], str[n - smallest - 1]] = swap(str[n - i - 1], str[n - smallest - 1]);
str = reverse(str, i + 1, mid);
if
(n % 2 == 0)
str = reverse(str, mid + 1, n - i - 2);
else
str = reverse(str, mid + 2, n - i - 2);
return
true
;
}
function
printAllPalinPermutations(str, n)
{
if
(!(findPalindromicString(str, n))) {
console.log(
"-1"
);
return
;
}
do
{
console.log(str.join(
""
));
}
while
(nextPalin(str, n));
}
let str = Array.from(
"malayalam"
);
let n = str.length;
printAllPalinPermutations(str, n);