Check if given Parentheses expression is balanced or not - GeeksforGeeks

08 Apr, 2022
Given a string str of length N, consisting of ‘(‘ and ‘)‘ only, the task is to check whether it is balanced or not.Examples: 
Input: str = “((()))()()” Output: BalancedInput: str = “())((())” Output: Not Balanced  
Approach:  
Declare a Flag variable which denotes expression is balanced or not.
Initialise Flag variable with true and Count variable with 0.
Traverse through the given expressionIf we encounter an opening parentheses (, increase count by 1If we encounter a closing parentheses ), decrease count by 1If Count becomes negative at any point, then expression is said to be not balanced, so mark Flag as false and break from loop.
If we encounter an opening parentheses (, increase count by 1If we encounter a closing parentheses ), decrease count by 1If Count becomes negative at any point, then expression is said to be not balanced, so mark Flag as false and break from loop.
If we encounter an opening parentheses (, increase count by 1
If we encounter a closing parentheses ), decrease count by 1
If Count becomes negative at any point, then expression is said to be not balanced, so mark Flag as false and break from loop.
After traversing the expression, if Count is not equal to 0, it means the expression is not balanced so mark Flag as false.
Finally, if Flag is true, expression is balanced else not balanced.
Below is the implementation of the above approach: 
C
C++
Java
Python3
C#
Javascript
// C program of the above approach#include <stdbool.h>#include <stdio.h> // Function to check if// parentheses are balancedbool isBalanced(char exp[]){    // Initialising Variables    bool flag = true;    int count = 0;     // Traversing the Expression    for (int i = 0; exp[i] != '\0'; i++) {         if (exp[i] == '(') {            count++;        }        else {            // It is a closing parenthesis            count--;        }        if (count < 0) {            // This means there are            // more Closing parenthesis            // than opening ones            flag = false;            break;        }    }     // If count is not zero,    // It means there are more    // opening parenthesis    if (count != 0) {        flag = false;    }     return flag;} // Driver codeint main(){    char exp1[] = "((()))()()";     if (isBalanced(exp1))        printf("Balanced \n");    else        printf("Not Balanced \n");     char exp2[] = "())((())";     if (isBalanced(exp2))        printf("Balanced \n");    else        printf("Not Balanced \n");     return 0;}
// C++ program for the above approach. #include <bits/stdc++.h>using namespace std; // Function to check// if parentheses are balancedbool isBalanced(string exp){     // Initialising Variables    bool flag = true;    int count = 0;     // Traversing the Expression    for (int i = 0; i < exp.length(); i++) {         if (exp[i] == '(') {            count++;        }        else {             // It is a closing parenthesis            count--;        }        if (count < 0) {             // This means there are            // more Closing parenthesis            // than opening ones            flag = false;            break;        }    }     // If count is not zero,    // It means there are    // more opening parenthesis    if (count != 0) {        flag = false;    }     return flag;} // Driver codeint main(){    string exp1 = "((()))()()";     if (isBalanced(exp1))        cout << "Balanced \n";    else        cout << "Not Balanced \n";     string exp2 = "())((())";     if (isBalanced(exp2))        cout << "Balanced \n";    else        cout << "Not Balanced \n";     return 0;}
// Java program for the above approach.class GFG{ // Function to check// if parentheses are balancedpublic static boolean isBalanced(String exp){         // Initialising variables    boolean flag = true;    int count = 0;         // Traversing the expression    for(int i = 0; i < exp.length(); i++)    {        if (exp.charAt(i) == '(')        {            count++;        }        else        {                         // It is a closing parenthesis            count--;        }        if (count < 0)        {                         // This means there are            // more Closing parenthesis            // than opening ones            flag = false;            break;        }    }         // If count is not zero,    // It means there are    // more opening parenthesis    if (count != 0)    {        flag = false;    }    return flag;} // Driver codepublic static void main(String[] args){    String exp1 = "((()))()()";         if (isBalanced(exp1))        System.out.println("Balanced");    else        System.out.println("Not Balanced");         String exp2 = "())((())";         if (isBalanced(exp2))        System.out.println("Balanced");    else        System.out.println("Not Balanced");}} // This code is contributed by divyeshrabadiya07
# Python3 program for the above approach # Function to check if# parenthesis are balanceddef isBalanced(exp):     # Initialising Variables    flag = True    count = 0     # Traversing the Expression    for i in range(len(exp)):        if (exp[i] == '('):            count += 1        else:                         # It is a closing parenthesis            count -= 1         if (count < 0):             # This means there are            # more closing parenthesis            # than opening            flag = False            break     # If count is not zero ,    # it means there are more    # opening parenthesis    if (count != 0):        flag = False     return flag # Driver codeif __name__ == '__main__':          exp1 = "((()))()()"     if (isBalanced(exp1)):        print("Balanced")    else:        print("Not Balanced")     exp2 = "())((())"     if (isBalanced(exp2)):        print("Balanced")    else:        print("Not Balanced") # This code is contributed by himanshu77
// C# program for the above approach.using System; class GFG{ // Function to check// if parentheses are balancedpublic static bool isBalanced(String exp){         // Initialising variables    bool flag = true;    int count = 0;         // Traversing the expression    for(int i = 0; i < exp.Length; i++)    {        if (exp[i] == '(')        {            count++;        }        else        {                         // It is a closing parenthesis            count--;        }        if (count < 0)        {                         // This means there are            // more Closing parenthesis            // than opening ones            flag = false;            break;        }    }         // If count is not zero,    // It means there are    // more opening parenthesis    if (count != 0)    {        flag = false;    }    return flag;} // Driver codepublic static void Main(String[] args){    String exp1 = "((()))()()";         if (isBalanced(exp1))        Console.WriteLine("Balanced");    else        Console.WriteLine("Not Balanced");         String exp2 = "())((())";         if (isBalanced(exp2))        Console.WriteLine("Balanced");    else        Console.WriteLine("Not Balanced");}} // This code is contributed by Amit Katiyar
<script> // JavaScript program for the above approach // Function to check if// parenthesis are balancedfunction isBalanced(exp){     // Initialising Variables    let flag = true    let count = 0     // Traversing the Expression    for(let i=0;i<exp.length;i++){        if (exp[i] == '(')            count += 1        else                         // It is a closing parenthesis            count -= 1         if (count < 0){             // This means there are            // more closing parenthesis            // than opening            flag = false            break        }    }    // If count is not zero ,    // it means there are more    // opening parenthesis    if (count != 0)        flag = false     return flag} // Driver code     let exp1 = "((()))()()" if (isBalanced(exp1))    document.write("Balanced","</br>")else    document.write("Not Balanced","</br>") let exp2 = "())((())" if (isBalanced(exp2))    document.write("Balanced","</br>")else    document.write("Not Balanced","</br>") // This code is contributed by shinjanpatra </script>
Balanced 
Not Balanced
 
Time complexity: O(N) Auxiliary Space: O(1) 
himanshu77
divyeshrabadiya07
amit143katiyar
shinjanpatra
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python program to check if a string is palindrome or not
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Array of Strings in C++ (5 Different Ways to Create)
Caesar Cipher in Cryptography
Reverse words in a given string
Length of the longest substring without repeating characters
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews
Remove duplicates from a given string