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

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

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



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

  • 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:nnInput: ((()))nOutput: 1nnInput: ()((nOutput: -1n



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

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.



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


Program:

@@coding::1@@


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:

@@coding::2@@


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


Recommended Programs







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

c