Check if rearranging Array elements can form a Palindrome or not | JavaScript Program to implement the above approach ; Function to check whether elements of an array can form a palindrome ; create an empty string to append elements of an array ; append each element to the string str to form a string so that we can solve it in easy way ; Create a freq array and initialize all values as 0 ; For each character in formed string , increment freq in the corresponding freq array ; Count odd occurring characters ; Return true if odd count is 0 or 1 , ; Drive code
let MAX = 256 function can_form_palindrome ( arr , n ) { let str = " " ; for ( let i = 0 ; i < n ; i ++ ) { str += toString ( arr [ i ] ) ; } let freq = new Array ( n ) . fill ( 0 ) ; for ( let i = 0 ; i < str . length ; i ++ ) { freq [ str . charCodeAt ( i ) ] ++ ; } let count = 0 ; for ( let i = 0 ; i < MAX ; i ++ ) { if ( freq [ i ] & 1 ) { count ++ ; } if ( count > 1 ) { return false ; } } return true ; } let arr = [ 1 , 2 , 3 , 1 , 2 ] ; let n = arr . length ; can_form_palindrome ( arr , n ) ? document . write ( " " ) : document . write ( " " ) ;