Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

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

  • Last Updated : 15 Jul, 2021

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:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: S = “cabaacba”
Output: 4
Explanation:
Below are the ways of partitioning the string satisfying the given conditions:



  1. 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.
  2. 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.
  3. 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.
  4. 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.
  • 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++




// 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 conditions
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) {
                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 Code
int main()
{
    string S = "mippiisssisssiipsspiim";
    int N = S.length();
    cout << countWays(S, N);
 
    return 0;
}

Java




// Java program for the above approach
import 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




# Python3 program for the above approach
 
# Function to find the total number
# of ways to partitiaon the string into
# two subset satisfying the conditions
def 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 Code
if __name__ == '__main__':
     
    S = "mippiisssisssiipsspiim"
    N = len(S)
     
    print(countWays(S, N))
 
# This code is contributed by mohit kumar 29
Output: 
504

 

Time Complexity: O(N*2N)
Auxiliary Space: O(N)




My Personal Notes arrow_drop_up
Recommended Articles
Page :