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.
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:
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).
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.