Count ways to split a string into two subsets that are reverse of each other - GeeksforGeeks

30 Mar, 2022
Given a string S consisting of N characters, the task is to find the number of ways to split the string into two subsets such that the first subset is the reverse of the second subset.
Examples:
Input: S = “cabaacba”Output: 4Explanation:Below are the ways of partitioning the string satisfying the given conditions:
Take the characters at the indices {0, 4, 6, 7} as the first subset and the remaining characters as the second subset. Then the string formed are “caba” and “abac” and the second string is the reverse of the first string.Take the characters at the indices {0, 3, 6, 7} as the first subset and remaining characters as the second subset. Then the string formed are “caba” and “abac” and the second string is the reverse of the first string.Take the characters at the indices {1, 2, 3, 5} as first subset and remaining characters as the second subset. Then the string formed are “abac” and “caba” and the second string is the reverse of first string.Take the characters at the indices {1, 2, 4, 5} as first subset and remaining characters as the second subset. Then the string formed are “abac” and “caba” and the second string is the reverse of the first string.
Take the characters at the indices {0, 4, 6, 7} as the first subset and the remaining characters as the second subset. Then the string formed are “caba” and “abac” and the second string is the reverse of the first string.
Take the characters at the indices {0, 3, 6, 7} as the first subset and remaining characters as the second subset. Then the string formed are “caba” and “abac” and the second string is the reverse of the first string.
Take the characters at the indices {1, 2, 3, 5} as first subset and remaining characters as the second subset. Then the string formed are “abac” and “caba” and the second string is the reverse of first string.
Take the characters at the indices {1, 2, 4, 5} as first subset and remaining characters as the second subset. Then the string formed are “abac” and “caba” and the second string is the reverse of the first string.
Therefore, the number of ways of splitting is 4.
Input: N = 11, S = “mippiisssisssiipsspiim”Output: 504
Approach: The given problem can be solved by using the concept of Bitmasking to generate all possible ways of splitting the string and check if there exists any such splitting of the string which is reverse of one another. Follow the steps below to solve the problem:
Initialize a variable, say ans as 0 to store the total number of ways of partitioning the string.
Iterate over the range [0, 2N] using a variable mask and perform the following steps:Initialize two strings say X and Y to store the characters of the first subset and second subset.Iterate over the range [0, N] and if the ith bit is set in the integer mask then append the character S[i] to X. Otherwise append the character S[i] to Y.Reverse the string Y and then check if the first string X is equal to the second string Y then increment ans by 1.
Initialize two strings say X and Y to store the characters of the first subset and second subset.
Iterate over the range [0, N] and if the ith bit is set in the integer mask then append the character S[i] to X. Otherwise append the character S[i] to Y.
Reverse the string Y and then check if the first string X is equal to the second string Y then increment ans by 1.
After completing the above steps, print the value of ans as the total number of ways.
Below is the implementation of the above approach:
C++
Java
Python3
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the total number// of ways to partitiaon the string into// two subset satisfying the conditionsint countWays(string S, int N){    // Stores the resultant number of    // ways of splitting    int ans = 0;     // Iterate over the range [0, 2^N]    for (int mask = 0;         mask < (1 << N); mask++) {         string X, Y;         // Traverse the string S        for (int i = 0; i < N; i++) {             // If ith bit is set, then            // append the character            // S[i] to X            if (mask >> i & 1) {                X += S[i];            }             // Otherwise, append the            // character S[i] to Y            else {                Y += S[i];            }        }         // Reverse the second string        reverse(Y.begin(), Y.end());         // If X is equal to Y        if (X == Y) {            ans++;        }    }     // Return the total number of ways    return ans;} // Driver Codeint main(){    string S = "mippiisssisssiipsspiim";    int N = S.length();    cout << countWays(S, N);     return 0;}
// Java program for the above approachimport java.lang.*;import java.io.*;import java.util.*; class GFG {             // Function to find the total number    // of ways to partitiaon the String into    // two subset satisfying the conditions    static int countWays(String S, int N)    {        // Stores the resultant number of        // ways of splitting        int ans = 0;             // Iterate over the range [0, 2^N]        for (int mask = 0;             mask < (1 << N); mask++) {                 String X="" , Y="";                 // Traverse the String S            for (int i = 0; i < N; i++) {                     // If ith bit is set, then                // append the character                // S[i] to X                if ((mask >> i & 1) == 1) {                    X += S.charAt(i);                }                     // Otherwise, append the                // character S[i] to Y                else {                    Y += S.charAt(i);                }            }                 // Reverse the second String            Y = new StringBuilder(Y).reverse().toString();            // If X is equal to Y            if (X.equals(Y)) {                ans++;            }        }             // Return the total number of ways        return ans;    }         // Driver Code    public static void main (String[] args)    {        String S = "mippiisssisssiipsspiim";        int N = S.length();        System.out.println(countWays(S, N));    }} // This code is contributed by shubhamsingh10
# Python3 program for the above approach # Function to find the total number# of ways to partitiaon the string into# two subset satisfying the conditionsdef countWays(S, N):         # Stores the resultant number of    # ways of splitting    ans = 0     # Iterate over the range [0, 2^N]    for mask in range((1 << N)):        X, Y = "",""         # Traverse the string S        for i in range(N):                         # If ith bit is set, then            # append the character            # S[i] to X            if (mask >> i & 1):                X += S[i]                             # Otherwise, append the            # character S[i] to Y            else:                Y += S[i]                         # Reverse the second string        Y = Y[::-1]                 # If X is equal to Y        if (X == Y):            ans += 1                 # Return the total number of ways    return ans # Driver Codeif __name__ == '__main__':         S = "mippiisssisssiipsspiim"    N = len(S)         print(countWays(S, N)) # This code is contributed by mohit kumar 29
<script> // JavaScript program for the above approach // Function to find the total number// of ways to partitiaon the string into// two subset satisfying the conditionsfunction countWays(S, N){         // Stores the resultant number of    // ways of splitting    let ans = 0     // Iterate over the range [0, 2^N]    for(let mask=0;mask<(1 << N);mask++){        let X = ""        let Y = ""         // Traverse the string S        for(let i=0;i<N;i++){                         // If ith bit is set, then            // append the character            // S[i] to X            if (mask >> i & 1)                X += S[i]                             // Otherwise, append the            // character S[i] to Y            else                Y += S[i]        }                         // Reverse the second string        Y = Y.split("").reverse().join("")                 // If X is equal to Y        if (X == Y)            ans += 1    }                 // Return the total number of ways    return ans} // Driver Code     let S = "mippiisssisssiipsspiim"let N = S.length     document.write(countWays(S, N)) // This code is contributed by shinjanpatra </script>
504
 
Time Complexity: O(N*2N)Auxiliary Space: O(N)
mohit kumar 29
SHUBHAMSINGH10
shinjanpatra
partition
subset
Mathematical
Strings
Strings
Mathematical
subset
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Program to find GCD or HCF of two numbers
Prime Numbers
Program to find sum of elements in a given array
Write a program to reverse an array or string
Reverse a string in Java
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not