Number of ways to partition a string into two balanced subsequences

Given a string ‘S’ consisting of open and closed brackets, the task is find the number of ways in which each character of ‘S’ can be assigned to either a string ‘X’ or string ‘Y’ (both initially empty) such that the strings formed by X and Y are balanced. It can be assumed that ‘S’ is itself balanced.

Examples:

Input: S = "(())"
Output: 6
Valid assignments are :
X = "(())" and Y = "" [All characters in X]
X = "" and Y = "(())" [Nothing in X]
X = "()" and Y = "()" [1st and 3rd characters in X]
X = "()" and Y = "()" [2nd and 3rd characters in X]
X = "()" and Y = "()" [2nd and 4th characters in X]
X = "()" and Y = "()" [1st and 4th characters in X]

Input: S = "()()"
Output: 4
X = "()()", Y = ""
X = "()", Y = "()"  [1st and 2nd in X]
X = "()", Y = ""  [1st and 4th in X]
X = "", Y = "()()"


A simple approach: We can generate every possible way of assigning the characters, and check if the strings formed are balanced or not. There are 2n assignments, valid or invalid, and it takes O(n) time to check if the strings formed are balanced or not. Therefore the time complexity of this approach is O(n * 2n).

An efficient approach (Dynamic programming): We can solve this problem in a more efficient manner using Dynamic Programming. We can describe the current state of assignment using three variables: the index i of the character to be assigned, and the strings formed by X and Y up to that state. Passing the whole strings to function calls will result in high memory requirements, so we can replace them with count variables cx and cy. We will increment the count variable for every opening bracket and decrement it for every closing bracket. The time and space complexity of this approach is O(n3).

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of
// the above approach
#include <bits/stdc++.h>
using namespace std;
  
// For maximum length of input string
const int MAX = 10;
  
// Declaring the DP table
int F[MAX][MAX][MAX];
  
// Function to calculate the
// number of valid assignments
int noOfAssignments(string& S, int& n, int i,
                    int c_x, int c_y)
{
    if (F[i][c_x][c_y] != -1)
        return F[i][c_x][c_y];
  
    if (i == n) {
  
        // Return 1 if both
        // subsequences are balanced
        F[i][c_x][c_y] = !c_x && !c_y;
        return F[i][c_x][c_y];
    }
  
    // Increment the count
    // if it an opening bracket
    if (S[i] == '(') {
        F[i][c_x][c_y]
            = noOfAssignments(S, n, i + 1,
                              c_x + 1, c_y)
              + noOfAssignments(S, n, i + 1,
                                c_x, c_y + 1);
        return F[i][c_x][c_y];
    }
  
    F[i][c_x][c_y] = 0;
  
    // Decrement the count
    // if it a closing bracket
    if (c_x)
        F[i][c_x][c_y]
            += noOfAssignments(S, n, i + 1,
                               c_x - 1, c_y);
  
    if (c_y)
        F[i][c_x][c_y]
            += noOfAssignments(S, n, i + 1,
                               c_x, c_y - 1);
  
    return F[i][c_x][c_y];
}
  
// Driver code
int main()
{
    string S = "(())";
    int n = S.length();
  
    // Initializing the DP table
    memset(F, -1, sizeof(F));
  
    // Intitial value for c_x
    // and c_y is zero
    cout << noOfAssignments(S, n, 0, 0, 0);
  
    return 0;
}

chevron_right


Output:

6

Optimized Dynamic Programming approach: We can create a prefix array to store the count variable ci for the substring S[0 : i + 1]. We can observe that the sum of c_x and c_y will always be equal to the count variable for the whole string. By exploiting this property, we can reduce our dynamic programming approach to two states. A prefix array can be created in linear complexity, so the time and space complexity of this approach is O(n2).

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of
// the above approach
#include <bits/stdc++.h>
using namespace std;
  
// For maximum length of input string
const int MAX = 10;
  
// Declaring the DP table
int F[MAX][MAX];
  
// Declaring the prefix array
int C[MAX];
  
// Function to calculate the
// number of valid assignments
int noOfAssignments(string& S, int& n,
                    int i, int c_x)
{
    if (F[i][c_x] != -1)
        return F[i][c_x];
  
    if (i == n) {
  
        // Return 1 if X is
        // balanced.
        F[i][c_x] = !c_x;
        return F[i][c_x];
    }
  
    int c_y = C[i] - c_x;
  
    // Increment the count
    // if it an opening bracket
    if (S[i] == '(') {
        F[i][c_x]
            = noOfAssignments(S, n, i + 1,
                              c_x + 1)
              + noOfAssignments(S, n,
                                i + 1, c_x);
        return F[i][c_x];
    }
  
    F[i][c_x] = 0;
  
    // Decrement the count
    // if it a closing bracket
    if (c_x)
        F[i][c_x]
            += noOfAssignments(S, n,
                               i + 1, c_x - 1);
  
    if (c_y)
        F[i][c_x]
            += noOfAssignments(S, n,
                               i + 1, c_x);
  
    return F[i][c_x];
}
  
// Driver code
int main()
{
    string S = "()";
    int n = S.length();
  
    // Initializing the DP table
    memset(F, -1, sizeof(F));
  
    C[0] = 0;
  
    // Creating the prefix array
    for (int i = 0; i < n; ++i)
        if (S[i] == '(')
            C[i + 1] = C[i] + 1;
        else
            C[i + 1] = C[i] - 1;
  
    // Initial value for c_x
    // and c_y is zero
    cout << noOfAssignments(S, n, 0, 0);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
  
public class GFG {
  
// For maximum length of input string 
    static int MAX = 10;
  
// Declaring the DP table 
    static int F[][] = new int[MAX][MAX];
  
// Declaring the prefix array 
    static int C[] = new int[MAX];
  
// Function to calculate the 
// number of valid assignments 
    static int noOfAssignments(String S, int n, int i, int c_x) {
        if (F[i][c_x] != -1) {
            return F[i][c_x];
        }
  
        if (i == n) {
  
            // Return 1 if X is 
            // balanced. 
            if (c_x == 1) {
                F[i][c_x] = 0;
            } else {
                F[i][c_x] = 1;
            }
  
            return F[i][c_x];
        }
  
        int c_y = C[i] - c_x;
  
        // Increment the count 
        // if it an opening bracket 
        if (S.charAt(i) == '(') {
            F[i][c_x]
                    = noOfAssignments(S, n, i + 1,
                            c_x + 1)
                    + noOfAssignments(S, n,
                            i + 1, c_x);
            return F[i][c_x];
        }
  
        F[i][c_x] = 0;
  
        // Decrement the count 
        // if it a closing bracket 
        if (c_x == 1) {
            F[i][c_x]
                    += noOfAssignments(S, n,
                            i + 1, c_x - 1);
        }
  
        if (c_y == 1) {
            F[i][c_x]
                    += noOfAssignments(S, n,
                            i + 1, c_x);
        }
  
        return F[i][c_x];
    }
  
// Driver code 
    public static void main(String[] args) {
        String S = "()";
        int n = S.length();
  
        // Initializing the DP table 
        for (int i = 0; i < MAX; i++) {
            for (int j = 0; j < MAX; j++) {
                F[i][j] = -1;
            }
        }
  
        C[0] = 0;
  
        // Creating the prefix array 
        for (int i = 0; i < n; ++i) {
            if (S.charAt(i) == '(') {
                C[i + 1] = C[i] + 1;
            } else {
                C[i + 1] = C[i] - 1;
            }
        }
  
        // Initial value for c_x 
        // and c_y is zero 
        System.out.println(noOfAssignments(S, n, 0, 0));
  
    }
}
// This code is contributed by 29AjayKumar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach
   
using System;
public class GFG {
   
// For maximum length of input string 
    static int MAX = 10;
   
// Declaring the DP table 
    static int[,] F = new int[MAX,MAX];
   
// Declaring the prefix array 
    static int[] C = new int[MAX];
   
// Function to calculate the 
// number of valid assignments 
    static int noOfAssignments(string S, int n, int i, int c_x) {
        if (F[i,c_x] != -1) {
            return F[i,c_x];
        }
   
        if (i == n) {
   
            // Return 1 if X is 
            // balanced. 
            if (c_x == 1) {
                F[i,c_x] = 0;
            } else {
                F[i,c_x] = 1;
            }
   
            return F[i,c_x];
        }
   
        int c_y = C[i] - c_x;
   
        // Increment the count 
        // if it an opening bracket 
        if (S[i] == '(') {
            F[i,c_x]
                    = noOfAssignments(S, n, i + 1,
                            c_x + 1)
                    + noOfAssignments(S, n,
                            i + 1, c_x);
            return F[i,c_x];
        }
   
        F[i,c_x] = 0;
   
        // Decrement the count 
        // if it a closing bracket 
        if (c_x == 1) {
            F[i,c_x]
                    += noOfAssignments(S, n,
                            i + 1, c_x - 1);
        }
   
        if (c_y == 1) {
            F[i,c_x]
                    += noOfAssignments(S, n,
                            i + 1, c_x);
        }
   
        return F[i,c_x];
    }
   
// Driver code 
    public static void Main() {
        string S = "()";
        int n = S.Length;
   
        // Initializing the DP table 
        for (int i = 0; i < MAX; i++) {
            for (int j = 0; j < MAX; j++) {
                F[i,j] = -1;
            }
        }
   
        C[0] = 0;
   
        // Creating the prefix array 
        for (int i = 0; i < n; ++i) {
            if (S[i] == '(') {
                C[i + 1] = C[i] + 1;
            } else {
                C[i + 1] = C[i] - 1;
            }
        }
   
        // Initial value for c_x 
        // and c_y is zero 
        Console.WriteLine(noOfAssignments(S, n, 0, 0));
   
    }
}
// This code is contributed by Ita_c.

chevron_right


Output:

2


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : 29AjayKumar, Ita_c