Print the arranged positions of characters to make palindrome | Maximum number of characters ; Insert all positions of every character in the given string . ; find the number of odd elements . Takes O ( n ) ; A palindrome cannot contain more than 1 odd characters ; Print positions in first half of palindrome ; Consider one instance odd character ; Print positions in second half of palindrome ; Driver code
var MAX = 256 ; function printPalindromePos ( str ) { var pos = Array . from ( Array ( MAX ) , ( ) => Array ( ) ) ; var n = str . length ; for ( var i = 0 ; i < n ; i ++ ) pos [ str [ i ] . charCodeAt ( 0 ) ] . push ( i + 1 ) ; var oddCount = 0 ; var oddChar ; for ( var i = 0 ; i < MAX ; i ++ ) { if ( pos [ i ] . length % 2 != 0 ) { oddCount ++ ; oddChar = i ; } } if ( oddCount > 1 ) document . write ( " " ) ; for ( var i = 0 ; i < MAX ; i ++ ) { var mid = pos [ i ] . length / 2 ; for ( var j = 0 ; j < mid ; j ++ ) document . write ( pos [ i ] [ j ] + " " ) ; } if ( oddCount > 0 ) { var last = pos [ oddChar ] . length - 1 ; document . write ( pos [ oddChar ] [ last ] + " " ) ; pos [ oddChar ] . pop ( ) ; } for ( var i = MAX - 1 ; i >= 0 ; i -- ) { var count = pos [ i ] . length ; for ( var j = count / 2 ; j < count ; j ++ ) document . write ( pos [ i ] [ j ] + " " ) ; } } var s = " " ; printPalindromePos ( s ) ;