VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-given-parentheses-expression-is-balanced-or-not/

⇱ Check for balanced with only one type of brackets - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check for balanced with only one type of brackets

Last Updated : 20 Jun, 2025

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 1:

  • 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:


Output
Balanced 
Not Balanced 

Time complexity: O(N) 
Auxiliary Space: O(1)

Approach 2: Using Stack

  • Declare stack.
  • Iterate string using for loop charAt() method.
  • If it is an opening bracket then push it to stack
  • else if it is closing bracket and stack is empty then return 0.
  • else continue iterating till the end of the string.
  • at every step check top element of stack using peek() and pop() element accordingly
  • end loop

Output
Valid

Time complexity: O(N) 
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: