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: Balanced
Input: 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 expression
- 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 program of the above approach #include <stdbool.h> #include <stdio.h> // Function to check if // parentheses are balanced bool 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 code int 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++
// C++ program for the above approach. #include <bits/stdc++.h> using namespace std; // Function to check // if parentheses are balanced 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 code int 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
// Java program for the above approach. class GFG{ // Function to check // if parentheses are balanced public 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 code public 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
# Python3 program for the above approach # Function to check if # parenthesis are balanced def 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 code if __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 |
Balanced Not Balanced
Time complexity: O(N)
Auxiliary Space: O(1)
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.
Recommended Posts:
- Check for balanced parentheses in an expression
- Check for balanced parentheses in an expression | O(1) space
- Check for balanced parentheses in an expression | O(1) space | O(N^2) time complexity
- Check for balanced parentheses in Python
- Count pairs of parentheses sequences such that parentheses are balanced
- Length of longest balanced parentheses prefix
- Balanced expression with replacement
- Minimum number of bracket reversals needed to make an expression balanced
- Minimum number of bracket reversals needed to make an expression balanced | Set - 2
- Check if the Depth of Parentheses is correct in the given String
- Check if the number is balanced
- Check if expression contains redundant bracket or not | Set 2
- Check if an URL is valid or not using Regular Expression
- How to check string is alphanumeric or not using Regular Expression
- How to check Aadhar number is valid or not using Regular Expression
- Check if a binary string has a 0 between 1s or not | Set 2 (Regular Expression Approach)
- Check if a string contains only alphabets in Java using Lambda expression
- Check if a given string is a valid number (Integer or Floating Point) in Java | SET 2 (Regular Expression approach)
- Check if the bracket sequence can be balanced with at most one change in the position of a bracket
- Score of Parentheses using Tree
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.

