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:
OutputBalanced
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
Time complexity: O(N)
Auxiliary Space: O(1)