Check if rearranging Array elements can form a Palindrome or not | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX  256 NEW_LINE bool can_form_palindrome ( int arr [ ] , int n ) { string str = " " ; for ( int i = 0 ; i < n ; i ++ ) { str += arr [ i ] ; } int freq [ MAX ] = { 0 } ; for ( int i = 0 ; str [ i ] ; i ++ ) { freq [ str [ i ] ] ++ ; } int count = 0 ; for ( int i = 0 ; i < MAX ; i ++ ) { if ( freq [ i ] & 1 ) { count ++ ; } if ( count > 1 ) { return false ; } } return true ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 1 , 2 } ; int n = sizeof ( arr ) / sizeof ( int ) ; can_form_palindrome ( arr , n ) ? cout << " YES " : cout << " NO " ; return 0 ; }