Open In App

Check for Balanced Brackets in an expression (well-formedness)

Last Updated : 04 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an expression string exp, write a program to examine whether the pairs and the orders of “{“, “}”, “(“, “)”, “[“, “]” are correct in the given expression.

Example

Input: exp = “[()]{}{[()()]()}” 
Output: Balanced
Explanation: all the brackets are well-formed

Input: exp = “[(])” 
Output: Not Balanced 
Explanation: 1 and 4 brackets are not balanced because 
there is a closing ‘]’ before the closing ‘(‘

Recommended Practice

Check for Balanced Bracket expression using Stack:

The idea is to put all the opening brackets in the stack. Whenever you hit a closing bracket, search if the top of the stack is the opening bracket of the same nature. If this holds then pop the stack and continue the iteration. In the end if the stack is empty, it means all brackets are balanced or well-formed. Otherwise, they are not balanced.

Illustration: 
Below is the illustration of the above approach.

Follow the steps mentioned below to implement the idea:

  • Declare a character stack (say temp).
  • Now traverse the 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 the stack and if the popped character is the matching starting bracket then fine.
    • Else brackets are Not Balanced.
  • After complete traversal, if some starting brackets are left in the stack then the expression is Not balanced, else Balanced.

Below is the implementation of the above approach:

C++




// C++ program to check for balanced brackets.
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if brackets are balanced
bool areBracketsBalanced(string expr)
{
    // Declare a stack to hold the previous brackets.
    stack<char> temp;
    for (int i = 0; i < expr.length(); i++) {
        if (temp.empty()) {
             
            // If the stack is empty
            // just push the current bracket
            temp.push(expr[i]);
        }
        else if ((temp.top() == '(' && expr[i] == ')')
                 || (temp.top() == '{' && expr[i] == '}')
                 || (temp.top() == '[' && expr[i] == ']')) {
             
            // If we found any complete pair of bracket
            // then pop
            temp.pop();
        }
        else {
            temp.push(expr[i]);
        }
    }
    if (temp.empty()) {
         
        // If stack is empty return true
        return true;
    }
    return false;
}
 
// Driver code
int main()
{
    string expr = "{()}[]";
 
    // Function call
    if (areBracketsBalanced(expr))
        cout << "Balanced";
    else
        cout << "Not Balanced";
    return 0;
}


C




#include <stdio.h>
#include <stdlib.h>
#define bool int
 
// Structure of a stack node
struct sNode {
    char data;
    struct sNode* next;
};
 
// Function to push an item to stack
void push(struct sNode** top_ref, int new_data);
 
// Function to pop an item from stack
int pop(struct sNode** top_ref);
 
// Returns 1 if character1 and character2 are matching left
// and right Brackets
bool isMatchingPair(char character1, char character2)
{
    if (character1 == '(' && character2 == ')')
        return 1;
    else if (character1 == '{' && character2 == '}')
        return 1;
    else if (character1 == '[' && character2 == ']')
        return 1;
    else
        return 0;
}
 
// Return 1 if expression has balanced Brackets
bool areBracketsBalanced(char exp[])
{
    int i = 0;
 
    // Declare an empty character stack
    struct sNode* stack = NULL;
 
    // Traverse the given expression to check matching
    // brackets
    while (exp[i]) {
        // If the exp[i] is a starting bracket then push
        // it
        if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
            push(&stack, exp[i]);
 
        // If exp[i] is an ending bracket then pop from
        // stack and check if the popped bracket is a
        // matching pair*/
        if (exp[i] == '}' || exp[i] == ')'
            || exp[i] == ']') {
 
            // If we see an ending bracket without a pair
            // then return false
            if (stack == NULL)
                return 0;
 
            // Pop the top element from stack, if it is not
            // a pair bracket of character then there is a
            // mismatch.
            // his happens for expressions like {(})
            else if (!isMatchingPair(pop(&stack), exp[i]))
                return 0;
        }
        i++;
    }
 
    // If there is something left in expression then there
    // is a starting bracket without a closing
    // bracket
    if (stack == NULL)
        return 1; // balanced
    else
        return 0; // not balanced
}
 
// Driver code
int main()
{
    char exp[100] = "{()}[]";
 
    // Function call
    if (areBracketsBalanced(exp))
        printf("Balanced \n");
    else
        printf("Not Balanced \n");
    return 0;
}
 
// Function to push an item to stack
void push(struct sNode** top_ref, int new_data)
{
    // allocate node
    struct sNode* new_node
        = (struct sNode*)malloc(sizeof(struct sNode));
 
    if (new_node == NULL) {
        printf("Stack overflow n");
        getchar();
        exit(0);
    }
 
    // put in the data
    new_node->data = new_data;
 
    // link the old list of the new node
    new_node->next = (*top_ref);
 
    // move the head to point to the new node
    (*top_ref) = new_node;
}
 
// Function to pop an item from stack
int pop(struct sNode** top_ref)
{
    char res;
    struct sNode* top;
 
    // If stack is empty then error
    if (*top_ref == NULL) {
        printf("Stack overflow n");
        getchar();
        exit(0);
    }
    else {
        top = *top_ref;
        res = top->data;
        *top_ref = top->next;
        free(top);
        return res;
    }
}


Java




// Java program for checking
// balanced brackets
import java.util.*;
 
public class BalancedBrackets {
 
    // function to check if brackets are balanced
    static boolean areBracketsBalanced(String expr)
    {
        // Using ArrayDeque is faster than using Stack class
        Deque<Character> stack
            = new ArrayDeque<Character>();
 
        // Traversing the Expression
        for (int i = 0; i < expr.length(); i++) {
            char x = expr.charAt(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.isEmpty())
                return false;
            char 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.isEmpty());
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String expr = "([{}])";
 
        // Function call
        if (areBracketsBalanced(expr))
            System.out.println("Balanced ");
        else
            System.out.println("Not Balanced ");
    }
}


Python3




# Python3 program to check for
# balanced brackets.
 
# function to check if
# brackets are balanced
 
 
def areBracketsBalanced(expr):
    stack = []
 
    # Traversing the Expression
    for char in expr:
        if char in ["(", "{", "["]:
 
            # Push the element in the stack
            stack.append(char)
        else:
 
            # IF current character is not opening
            # bracket, then it must be closing.
            # So stack cannot be empty at this point.
            if not stack:
                return False
            current_char = stack.pop()
            if current_char == '(':
                if char != ")":
                    return False
            if current_char == '{':
                if char != "}":
                    return False
            if current_char == '[':
                if char != "]":
                    return False
 
    # Check Empty Stack
    if stack:
        return False
    return True
 
 
# Driver Code
if __name__ == "__main__":
    expr = "{()}[]"
 
    # Function call
    if areBracketsBalanced(expr):
        print("Balanced")
    else:
        print("Not Balanced")
 
# This code is contributed by AnkitRai01 and improved
# by Raju Pitta


C#




// C# program for checking
// balanced Brackets
using System;
using System.Collections.Generic;
 
public class BalancedBrackets {
    public class stack {
        public int top = -1;
        public char[] items = new char[100];
 
        public void push(char x)
        {
            if (top == 99) {
                Console.WriteLine("Stack full");
            }
            else {
                items[++top] = x;
            }
        }
 
        char pop()
        {
            if (top == -1) {
                Console.WriteLine("Underflow error");
                return '\0';
            }
            else {
                char element = items[top];
                top--;
                return element;
            }
        }
 
        Boolean isEmpty()
        {
            return (top == -1) ? true : false;
        }
    }
 
    // Returns true if character1 and character2
    // are matching left and right brackets */
    static Boolean isMatchingPair(char character1,
                                  char character2)
    {
        if (character1 == '(' && character2 == ')')
            return true;
        else if (character1 == '{' && character2 == '}')
            return true;
        else if (character1 == '[' && character2 == ']')
            return true;
        else
            return false;
    }
 
    // Return true if expression has balanced
    // Brackets
    static Boolean areBracketsBalanced(char[] exp)
    {
        // Declare an empty character stack */
        Stack<char> st = new Stack<char>();
 
        // Traverse the given expression to
        //   check matching brackets
        for (int i = 0; i < exp.Length; i++) {
            // If the exp[i] is a starting
            // bracket then push it
            if (exp[i] == '{' || exp[i] == '('
                || exp[i] == '[')
                st.Push(exp[i]);
 
            //  If exp[i] is an ending bracket
            //  then pop from stack and check if the
            //   popped bracket is a matching pair
            if (exp[i] == '}' || exp[i] == ')'
                || exp[i] == ']') {
 
                // If we see an ending bracket without
                //   a pair then return false
                if (st.Count == 0) {
                    return false;
                }
 
                // Pop the top element from stack, if
                // it is not a pair brackets of
                // character then there is a mismatch. This
                // happens for expressions like {(})
                else if (!isMatchingPair(st.Pop(),
                                         exp[i])) {
                    return false;
                }
            }
        }
 
        // If there is something left in expression
        // then there is a starting bracket without
        // a closing bracket
 
        if (st.Count == 0)
            return true; // balanced
        else {
            // not balanced
            return false;
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        char[] exp = { '{', '(', ')', '}', '[', ']' };
 
        // Function call
        if (areBracketsBalanced(exp))
            Console.WriteLine("Balanced ");
        else
            Console.WriteLine("Not Balanced ");
    }
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
 
// Javascript program for checking
// balanced brackets
 
// Function to check if brackets are balanced
function 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 code
let expr = "([{}])";
 
// Function call
if (areBracketsBalanced(expr))
    document.write("Balanced ");
else
    document.write("Not Balanced ");
 
// This code is contributed by rag2127
 
</script>


Output

Balanced

Time Complexity: O(N), Iteration over the string of size N one time.
Auxiliary Space: O(N) for the stack. 

Check for Balanced Bracket expression without using stack :

Following are the steps to be followed:

  • Initialize a variable i with -1.
  • Iterate through the string and 
    • If it is an open bracket then increment the counter by 1 and replace ith character of the string with the opening bracket.
    • Else if it is a closing bracket of the same corresponding opening bracket (opening bracket stored in exp[i]) then decrement i by 1.
  • At last, if we get i = -1, then the string is balanced and we will return true. Otherwise, the function will return false.

Below is the implementation of the above approach:

C++




#include <iostream>
 
using namespace std;
 
 bool areBracketsBalanced(string s) {
        int i=-1;
        for(auto& ch:s){
            if(ch=='(' || ch=='{' || ch=='[')
                s[++i]=ch;
            else{
                if(i>=0 && ((s[i]=='(' && ch==')') || (s[i]=='{' && ch=='}') || (s[i]=='[' && ch==']')))
                    i--;
                else
                    return false;
            }
        }
        return i==-1;
    }
 
int main()
{
    string expr = "{()}[]";
 
    // Function call
    if (areBracketsBalanced(expr))
        cout << "Balanced";
    else
        cout << "Not Balanced";
    return 0;
}


Java




public class GFG {
    public static boolean areBracketsBalanced(String s)
    {
        int i = -1;
        char[] stack = new char[s.length()];
        for (char ch : s.toCharArray()) {
            if (ch == '(' || ch == '{' || ch == '[')
                stack[++i] = ch;
            else {
                if (i >= 0
                    && ((stack[i] == '(' && ch == ')')
                        || (stack[i] == '{' && ch == '}')
                        || (stack[i] == '[' && ch == ']')))
                    i--;
                else
                    return false;
            }
        }
        return i == -1;
    }
 
    public static void main(String[] args)
    {
        String expr = "{()}[]";
 
        // Function call
        if (areBracketsBalanced(expr))
            System.out.println("Balanced");
        else
            System.out.println("Not Balanced");
    }
}


C#




// c# implementation
 
using System;
 
public class GFG {
    static bool areBracketsBalanced(string s) {
        int i = -1;
        char[] stack = new char[s.Length];
        foreach (char ch in s) {
            if (ch == '(' || ch == '{' || ch == '[')
                stack[++i] = ch;
            else {
                if (i >= 0 && ((stack[i] == '(' && ch == ')') || (stack[i] == '{' && ch == '}') || (stack[i] == '[' && ch == ']')))
                    i--;
                else
                    return false;
            }
        }
        return i == -1;
    }
 
    static void Main() {
        string expr = "{()}[]";
 
        // Function call
        if (areBracketsBalanced(expr))
            Console.WriteLine("Balanced");
        else
            Console.WriteLine("Not Balanced");
    }
}
// ksam24000


Python3




def are_brackets_balanced(s):
    stack = []
    for ch in s:
        if ch in ('(', '{', '['):
            stack.append(ch)
        else:
            if stack and ((stack[-1] == '(' and ch == ')') or
                          (stack[-1] == '{' and ch == '}') or
                          (stack[-1] == '[' and ch == ']')):
                stack.pop()
            else:
                return False
    return not stack
 
expr = "{()}[]"
 
# Function call
if are_brackets_balanced(expr):
    print("Balanced")
else:
    print("Not Balanced")


Javascript




function areBracketsBalanced(s) {
    let i = -1;
    let stack = [];
    for (let ch of s) {
        if (ch === '(' || ch === '{' || ch === '[') {
            stack.push(ch);
            i++;
        } else {
            if (i >= 0 && ((stack[i] === '(' && ch === ')') || (stack[i] === '{' && ch === '}') || (stack[i] === '[' && ch === ']'))) {
                stack.pop();
                i--;
            } else {
                return false;
            }
        }
    }
    return i === -1;
}
 
let expr = "{()}[]";
 
// Function call
if (areBracketsBalanced(expr))
    console.log("Balanced");
else
    console.log("Not Balanced");


Output

Balanced

Time Complexity: O(N), Iteration over the string of size N one time.
Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

C++ Program To Check For Balanced Brackets In An Expression (Well-Formedness) Using Stack
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  Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.   Algorithm:  Declar
2 min read
C Program To Check For Balanced Brackets In An Expression (Well-Formedness) Using Stack
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 Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution. Algorithm: Declare a c
4 min read
Java Program To Check For Balanced Brackets In An Expression (Well-Formedness) Using Stack
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  Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.   Algorithm:  Declar
2 min read
Python Program To Check For Balanced Brackets In An Expression (Well-Formedness) Using Stack
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  Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.   Algorithm:  Declar
2 min read
C# Program To Check For Balanced Brackets In An Expression (Well-Formedness) Using Stack
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  Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.   Algorithm:  Declar
3 min read
Javascript Program To Check For Balanced Brackets In An Expression (Well-Formedness) Using Stack
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  Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.   Algorithm:  Declar
2 min read
Print the balanced bracket expression using given brackets
Given four integers a, b, c and d which signifies the number of four types of brackets. "((""()"")(""))" The task is to print any balanced bracket expression using all the given brackets. If we cannot form a balanced bracket expression then print -1. In case of multiple answers, print any one. Examples: Input: a = 3, b = 1, c = 4, d = 3 Output: (((
6 min read
Check if it is possible to obtain a Balanced Parenthesis by shifting brackets to either end at most K times
Given a string S of size N consisting of only '(' and ')' only and a positive integer K, the task is to check if the given string can be made a valid parenthesis sequence by moving any characters of the string S to either end of the string at most K number of times. Examples: Input: S = ")(", K = 1Output: YesExplanation: Move S[0] to the end of the
8 min read
Balanced expressions such that given positions have opening brackets | Set 2
Given an integer n and an array of positions ‘position[]’ (1 &lt;= length(position[]) &lt;= 2n), find the number of ways of proper bracket expressions that can be formed of length 2n such that given positions have the opening bracket. Note: position[] array is given in the form of (1-based indexing) [0, 1, 1, 0]. Here 1 denotes the positions at whi
15+ min read
Print all Balanced Brackets Strings that can be formed by replacing wild card '?'
Given string str containing characters '?', '(' and ')', the task is to replace the '?' character with '(' or ')' and print all the strings containing balanced brackets Example: Input: str = "????"Output:()()(()) Input: str = "(()?"Output: (()) Approach: The given problem can be solved using recursion and backtracking. The idea is to substitute eve
10 min read
three90RightbarBannerImg