Javascript Program To Check For Balanced Brackets In An Expression (Well-Formedness) Using Stack

14 Dec, 2021
Given an expression string exp, write a program to examine whether the pairs and the orders of “{“, “}”, “(“, “)”, “[“, “]” are correct in exp.
Example: 
Input: exp = “[()]{}{[()()]()}” Output: Balanced
Input: exp = “[(])” Output: Not Balanced 
Algorithm: 
Declare a character stack S.
Now traverse the expression string exp. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced.
If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced.
If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.
If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else brackets are not balanced.
After complete traversal, if there is some starting bracket left in stack then “not balanced”
Below image is a dry run of the above approach:
Below is the implementation of the above approach:
Javascript
<script>  // Javascript program for checking// balanced brackets  // Function to check if brackets are balancedfunction areBracketsBalanced(expr){          // Using ArrayDeque is faster    // than using Stack class    let stack = [];      // Traversing the Expression    for(let i = 0; i < expr.length; i++)    {        let x = expr[i];          if (x == '(' || x == '[' || x == '{')        {                          // Push the element in the stack            stack.push(x);            continue;        }          // If current character is not opening        // bracket, then it must be closing.         // So stack cannot be empty at this point.        if (stack.length == 0)            return false;                      let check;        switch (x){        case ')':            check = stack.pop();            if (check == '{' || check == '[')                return false;            break;          case '}':            check = stack.pop();            if (check == '(' || check == '[')                return false;            break;          case ']':            check = stack.pop();            if (check == '(' || check == '{')                return false;            break;        }    }      // Check Empty Stack    return (stack.length == 0);}  // Driver codelet expr = "([{}])";  // Function callif (areBracketsBalanced(expr))    document.write("Balanced ");else    document.write("Not Balanced ");  // This code is contributed by rag2127  </script>
Balanced
Time Complexity: O(n) Auxiliary Space: O(n) for stack. 
Please refer complete article on Check for Balanced Brackets in an expression (well-formedness) using Stack for more details!
Amazon
Hike
Oracle
Parentheses-Problems
Snapdeal
Walmart
Wipro
Yatra.com
Zoho
Stack
Strings
Zoho
Amazon
Snapdeal
Hike
Oracle
Walmart
Wipro
Yatra.com
Strings
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Design a stack with operations on middle element
How to efficiently implement k stacks in a single array?
Real-time application of Data Structures
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Different Methods to Reverse a String in C++