Check if rearranging Array elements can form a Palindrome or not | Java implementation of 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
import java . io . * ; import java . util . Arrays ; class GFG { static int MAX = 256 ; static boolean can_form_palindrome ( int [ ] arr , int n ) { String str = " " ; for ( int i = 0 ; i < n ; i ++ ) { str += arr [ i ] ; } int freq [ ] = new int [ MAX ] ; Arrays . fill ( freq , 0 ) ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { freq [ str . charAt ( i ) ] ++ ; } int count = 0 ; for ( int i = 0 ; i < MAX ; i ++ ) { if ( ( freq [ i ] & 1 ) != 0 ) { count ++ ; } if ( count > 1 ) { return false ; } } return true ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 1 , 2 } ; int n = arr . length ; if ( can_form_palindrome ( arr , n ) ) System . out . println ( " YES " ) ; else System . out . println ( " NO " ) ; } }