Check if rearranging Array elements can form a Palindrome or not | 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 , ; Driver Code
def can_form_palindrome ( arr , n ) : NEW_LINE INDENT MAX = 256 NEW_LINE s = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT s = s + str ( arr [ i ] ) NEW_LINE DEDENT freq = [ 0 ] * MAX NEW_LINE for i in range ( N ) : NEW_LINE INDENT freq [ arr [ i ] ] = freq [ arr [ i ] ] + 1 NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT if ( freq [ i ] & 1 ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT if ( count > 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE if ( can_form_palindrome ( arr , N ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT