Count of sub-arrays whose elements can be re-arranged to form palindromes in C++

We are given an array of integer elements and the task is to calculate the count of sub-arrays that can be formed from the given array such that its elements can form a valid palindrome. Palindromes are the sequences that are arranged similarly from start and the end.

Input − int arr[] = { 3, 3, 1, 4, 2, 1, 5}

Output − Count of sub-arrays whose elements can be re-arranged to form palindromes are − 9

Explanation − The valid sub-arrays whose elements can be arranged to form a palindrome are {3}, {3}, {1}, {4}, {2}, {1}, {5}, {1, 2, 1} and {1, 3, 1}. So, the total count is 9.

Input − int arr[] = { 2, 5, 5, 2, 1}

Output − Count of sub-arrays whose elements can be re-arranged to form palindromes are − 8

Explanation − The valid sub-arrays whose elements can be arranged to form a palindrome are {2}, {5}, {5}, {2}, {1}, {5, 2, 5}, {2, 5, 2}, {2, 5, 5, 2}. So, the total count is 8.

Approach used in the below program is as follows

• Input an array of integer elements and calculate the size of an array and pass the data to the function for further processing.

• Declare a temporary variable count to store the sub-arrays of palindrome.

• Start loop FOR from 0 till the size of an array

• Inside the loop, declare a variable of type long long and set it as 1LL << arr[j] and set temp as temp ^ val

• Call a function inside a boolean variable that will return either true or false.

• Check IF temp is 0LL or ch is True then increment the count by 1

• Return the count

• Print the result.

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
bool check(long long temp){
return !(temp & (temp - 1LL));
}
int palindromes_rearrange(int arr[], int size){
int count = 0;
for (int i = 0; i < size; i++){
long long temp = 0LL;
for (int j = i; j < size; j++){
long long val = 1LL << arr[j];
temp = temp ^ val;
bool ch = check(temp);
if (temp == 0LL || ch){
count++;
}
}
}
return count;
}
int main(){
int arr[] = { 3, 3, 1, 4, 2, 1, 5};
int size = sizeof(arr) / sizeof(arr[0]);
cout<<"Count of sub-arrays whose elements can be re-arranged to form palindromes are:
"<<palindromes_rearrange(arr, size);
return 0;
}

Output

If we run the above code it will generate the following output −

Count of sub-arrays whose elements can be re-arranged to form palindromes are: 9

Updated on: 02-Dec-2020

144 Views