Explore
Placement Prep

Edit

Edit

# Balanced Parenthesis Checker | Program to check for balanced parenthesis in an expression

Published on 09 Mar 2020

Program to check for balanced parenthesis with and without using stack is discussed here. You can develop a parenthesis checker without using stack as well. But using stack can have several advantages.

• Using a stack to balance parenthesis will help you balance different types of grouping operators such as[],{}and()and verify that they are correctly nested.
• Using a stack will also help improve the efficiency of the code

Example:

Input: ((()))
Output: 1

Input: ()((
Output: -1


## Balanced Parenthesis Checker using Stack

The algorithm to check for balanced parenthesis with a stack is given below

• When any open symbol i.e, (, {, [ is encountered, it will be pushed in the stack.
• If any close symbol i.e, ), }, ] is encountered, any of the three can happen
• The TOS (Top Of Stack) is checked, if the encountered close symbol matches with its open symbol, then open symbol which is at TOS is popped out.(OR)
• The TOS (Top Of Stack) is checked, if the encountered close symbol does not match with its open symbol, then -1 is returned as there is no matching symbol. (OR)
• The TOS (Top Of Stack) is checked,if the stack is empty, then -1 is returned as there is no open symbol in the stack.

### Program:

C
C++
Java
Python 3

Output
Input- ((())) Output- Balanced

## Balanced Parenthesis Checker without using Stack

The algorithm to check for balanced parenthesis with a stack is given below.

• Input the expression to be checked.
• Use a temporary variable say count to keep track of number of opening braces in the expression.
• Search for closing parenthesis for the corresponding opening parenthesis in the expression.
• If the count of closing and opening parenthesis are the same, then the expression is said to be balanced.

### Program:

C++

Output
Input- ()(( Output- -1

Recommended Programs