Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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: 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 partition 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 partition 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 partition 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


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG {
 
  public static string Reverse( string s )
  {
    char[] charArray = s.ToCharArray();
    Array.Reverse(charArray);
    return new string(charArray);
  }
 
  // Function to find the total number
  // of ways to partition 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[i];
        }
 
        // Otherwise, append the
        // character S[i] to Y
        else {
          Y += S[i];
        }
      }
 
      // Reverse the second string
      Y = Reverse(Y);
 
      // 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;
    Console.WriteLine(countWays(S, N));
  }
}
 
// This code is contributed by phasing17


Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to find the total number
// of ways to partition the string into
// two subset satisfying the conditions
function 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>


Output: 

504

 

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



Last Updated : 07 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads