Count of Subsequences forming Palindrome with Binary representations
Given an array A[]. The task is to count the number of subsequences such that concatenation of binary representation of the numbers represents palindrome.
Examples:
Input: A[] = {1, 2, 3}
Output: 4
Explanation: Binary representation of all elements are {1, 10, 11}
here the concatenation of {1, 3} => 111 makes palindrome
similarly, concatenation of {1, 2, 3} => 11011 makes palindrome, and
element {1} and {3} already have a palindromic binary form
Hence, total 4 subsequences are possible whose binary concatenation makes palindromeInput: A[ ] = {4, 9, 3, 15, 23}
Output: 6
Approach: The problem can be solved by checking each subsequence for palindrome after converting the given array into the binary representation of each element.
Follow the steps to solve the problem:
- Firstly, replace all the integers of the array into their binary representation and store it into a vector of string.
- Now, find all the subsequence of the vector of string:
- Check, if the subsequence is a palindrome or not.
- If true, then increment the count.
- Lastly, print the count.
Below is the implementation of the above approach:
C++
// C++ implementation of above approach #include <bits/stdc++.h>using namespace std; // Function to convert array element into// their binary representationvector<string> convert(vector<int> arr, int n){ vector<string> v; int i, x; for (i = 0; i < n; i++) { x = arr[i]; string s; // Convert into binary one by one while (x) { int r = x % 2; s += to_string(r); x /= 2; } // Reverse the string and store // into vector v reverse(s.begin(), s.end()); v.push_back(s); } return v;} // Function to check palindromebool palindrome(string a, int i, int j){ while (i < j) { // If the integer at i is // not equal to j // then return false if (a[i] != a[j]) return false; i++; j--; } // All a[i] is equal to a[j] // then return true return true;} // Function to count palindromic subsequencesvoid countSubsequences(vector<string> arr, int i, string s, int& count){ // Check the condition of palindrome // if it is the leaf of recursion tree if (i == arr.size()) { int l = s.length(); // Check for palindrome and // increment count if (l > 0 && palindrome(s, 0, l - 1)) { count++; } } else { // Subsequence without including // the element at current index countSubsequences(arr, i + 1, s, count); // Concatenate string s += (arr[i]); // Subsequence including the element // at current index countSubsequences(arr, i + 1, s, count); } return;} // Function to find all the subsequencesint solve(vector<int>& arr){ int count = 0, i = 0; vector<string> v = convert(arr, arr.size()); // Recursive function call countSubsequences(v, i, "", count); return count;} // Driver codeint main(){ vector<int> arr = { 4, 9, 3, 15, 23 }; // First replace all the array element // to their binary form int count = solve(arr); cout << count; return 0;} |
6
Time Complexity: O(2N * N)
Auxiliary Space: O(N)

