Balanced expression with replacement

Given a string that contains only the following => ‘{‘, ‘}’, ‘(‘, ‘)’, ‘[’, ‘]’. At some places there is ‘X’ in place of any bracket. Determine whether by replacing all ‘X’s with appropriate bracket, is it possible to make a valid bracket sequence.

Prerequisite: Balanced Parenthesis Expression

Examples:

Input : S = "{(X[X])}"
Output : Balanced
The balanced expression after
replacing X with suitable bracket is:
{([[]])}.

Input : [{X}(X)]
Output : Not balanced
No substitution of X with any bracket
results in a balanced expression.

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: We have discussed a solution on verifying whether given parenthesis expression is balanced or not.
Following the same approach described in the article, a stack data structure is used for verifying whether given expression is balanced or not. For each type of character in string, the operations to be performed on stack are:

1. ‘{‘ or ‘(‘ or ‘[‘ : When current element of string is an opening bracket, push the element in stack.
2. ‘}’ or ‘]’ or ‘)’ : When current element of string is a closing bracket, pop the top element of the stack and check if it is a matching opening bracket for the closing bracket or not. If it is matching, then move to next element of string. If it is not, then current string is not balanced. It is also possible that the element popped from stack is ‘X’. In that case ‘X’ is a matching opening bracket because it is pushed in stack only when it is assumed to be an opening bracket as described in next step.
3. ‘X’ : When current element is X then it can either be a starting bracket or a closing bracket. First assume that it is a starting bracket and recursively call for next element by pushing X in stack. If the result of recursion is false then X is a closing bracket which matches the bracket at top of the stack (If stack is non-empty). So pop the top element and recursively call for next element. If the result of recursion is again false, then the expression is not balanced.

Also check for the case when stack is empty and current element is a closing bracket. In that case, the expression is not balanced.

Implementation:

C++

 // CPP program to determine whether given  // expression is balanced/ parenthesis  // expression or not. #include using namespace std;    // Function to check if two brackets are matching // or not. int isMatching(char a, char b) {     if ((a == '{' && b == '}') || (a == '[' && b == ']')         || (a == '(' && b == ')') || a == 'X')         return 1;     return 0; }    // Recursive function to check if given expression // is balanced or not. int isBalanced(string s, stack ele, int ind) {        // Base case.     // If the string is balanced then all the opening     // brackets had been popped and stack should be     // empty after string is traversed completely.     if (ind == s.length())          return ele.empty();        // variable to store element at the top of the stack.     char topEle;        // variable to store result of recursive call.     int res;        // Case 1: When current element is an opening bracket     // then push that element in the stack.     if (s[ind] == '{' || s[ind] == '(' || s[ind] == '[') {         ele.push(s[ind]);         return isBalanced(s, ele, ind + 1);     }        // Case 2: When current element is a closing bracket     // then check for matching bracket at the top of the     // stack.     else if (s[ind] == '}' || s[ind] == ')' || s[ind] == ']') {            // If stack is empty then there is no matching opening         // bracket for current closing bracket and the         // expression is not balanced.         if (ele.empty())              return 0;            topEle = ele.top();         ele.pop();            // Check bracket is matching or not.         if (!isMatching(topEle, s[ind]))              return 0;                    return isBalanced(s, ele, ind + 1);     }        // Case 3: If current element is 'X' then check     // for both the cases when 'X' could be opening     // or closing bracket.     else if (s[ind] == 'X') {         stack tmp = ele;         tmp.push(s[ind]);         res = isBalanced(s, tmp, ind + 1);         if (res)             return 1;         if (ele.empty())             return 0;         ele.pop();         return isBalanced(s, ele, ind + 1);     } }    int main() {     string s = "{(X}[]";     stack ele;     if (isBalanced(s, ele, 0))          cout << "Balanced";         else          cout << "Not Balanced";         return 0; }

Java

 import java.util.Stack;    // Java program to determine  // whether given expression  // is balanced/ parenthesis  // expression or not.  class GFG {     // Function to check if two      // brackets are matching or not.         static int isMatching(char a,             char b) {         if ((a == '{' && b == '}')                 || (a == '[' && b == ']')                 || (a == '(' && b == ')') || a == 'X') {             return 1;         }         return 0;     }        // Recursive function to      // check if given expression      // is balanced or not.      static int isBalanced(String s,             Stack ele,             int ind) {            // Base case.          // If the string is balanced          // then all the opening brackets          // had been popped and stack          // should be empty after string          // is traversed completely.          if (ind == s.length()) {             if (ele.size() == 0) {                 return 1;             } else {                 return 0;             }         }            // variable to store element          // at the top of the stack.          char topEle;            // variable to store result          // of recursive call.          int res;            // Case 1: When current element          // is an opening bracket          // then push that element          // in the stack.          if (s.charAt(ind) == '{'                 || s.charAt(ind) == '('                 || s.charAt(ind) == '[') {             ele.push(s.charAt(ind));             return isBalanced(s, ele, ind + 1);         } // Case 2: When current element          // is a closing bracket then          // check for matching bracket          // at the top of the stack.          else if (s.charAt(ind) == '}'                 || s.charAt(ind) == ')'                 || s.charAt(ind) == ']') {                // If stack is empty then there              // is no matching opening bracket              // for current closing bracket and              // the expression is not balanced.              if (ele.size() == 0) {                 return 0;             }                topEle = ele.peek();             ele.pop();                // Check bracket is              // matching or not.              if (isMatching(topEle, s.charAt(ind)) == 0) {                 return 0;             }                return isBalanced(s, ele, ind + 1);         } // Case 3: If current element          // is 'X' then check for both          // the cases when 'X' could be          // opening or closing bracket.          else if (s.charAt(ind) == 'X') {             Stack tmp = new Stack<>();             //because in java, direct assignment copies only reference and not the whole object             tmp.addAll(ele);              tmp.push(s.charAt(ind));             res = isBalanced(s, tmp, ind + 1);             if (res == 1) {                 return 1;             }             if (ele.size() == 0) {                 return 0;             }             ele.pop();             return isBalanced(s, ele, ind + 1);         }         return 1;     }        // Driver Code      public static void main(String[] args) {            String s = "{(X}[]";         Stack ele = new Stack();            if (isBalanced(s, ele, 0) != 0) {             System.out.println("Balanced");         } else {             System.out.println("Not Balanced");         }     } }

C#

 // C# program to determine  // whether given expression  // is balanced/ parenthesis  // expression or not. using System; using System.Collections.Generic;    class GFG {     // Function to check if two      // brackets are matching or not.     static int isMatching(char a,                            char b)     {         if ((a == '{' && b == '}') ||              (a == '[' && b == ']') ||              (a == '(' && b == ')') || a == 'X')             return 1;         return 0;     }            // Recursive function to      // check if given expression     // is balanced or not.     static int isBalanced(string s,                            Stack ele,                            int ind)     {                // Base case.         // If the string is balanced          // then all the opening brackets         // had been popped and stack          // should be empty after string          // is traversed completely.         if (ind == s.Length)          {             if (ele.Count == 0)                 return 1;             else                 return 0;         }                // variable to store element          // at the top of the stack.         char topEle;                // variable to store result         // of recursive call.         int res;                // Case 1: When current element         // is an opening bracket         // then push that element          // in the stack.         if (s[ind] == '{' ||              s[ind] == '(' ||             s[ind] == '[')          {             ele.Push(s[ind]);             return isBalanced(s, ele, ind + 1);         }                // Case 2: When current element         // is a closing bracket then          // check for matching bracket          // at the top of the stack.         else if (s[ind] == '}' ||                   s[ind] == ')' ||                   s[ind] == ']')         {                    // If stack is empty then there              // is no matching opening bracket              // for current closing bracket and              // the expression is not balanced.             if (ele.Count == 0)                  return 0;                    topEle = ele.Peek();             ele.Pop();                    // Check bracket is              // matching or not.             if (isMatching(topEle, s[ind]) == 0)                  return 0;                            return isBalanced(s, ele, ind + 1);         }                // Case 3: If current element          // is 'X' then check for both          // the cases when 'X' could be          // opening or closing bracket.         else if (s[ind] == 'X')          {             Stack tmp = ele;             tmp.Push(s[ind]);             res = isBalanced(s, tmp, ind + 1);             if (res == 1)                 return 1;             if (ele.Count == 0)                 return 0;             ele.Pop();             return isBalanced(s, ele, ind + 1);         }         return 1;     }            // Driver Code     static void Main()     {         string s = "{(X}[]";         Stack ele = new Stack();                    if (isBalanced(s, ele, 0) != 0)              Console.Write("Balanced");          else             Console.Write("Not Balanced");      } }    // This code is contributed by  // Manish Shaw(manishshaw1)

Output:

Balanced

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

My Personal Notes arrow_drop_up A Programmer and A Machine learning Enthusiast

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.

Article Tags :
Practice Tags :

3

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.