Site icon Study Algorithms

How can stacks be used for checking balancing of symbols?

Stacks can be used to check if the given expression has balanced symbols or not. The algorithm is very much useful in compilers. Each time parser reads one character at a time. If the character is an opening delimiter like ‘(‘ , ‘{‘ or ‘[‘ then it is PUSHED in to the stack. When a closing delimiter is encountered like ‘)’ , ‘}’ or ‘]’ is encountered, the stack is popped. The opening and closing delimiter are then compared. If they match, the parsing of the string continues. If they do not match, the parser indicates that there is an error on the line. A linear time O(n) algorithm based on stack can be given as:-

Examples:

EXAMPLE Valid? Description
(A+B) + (C-D) Yes The expression is having balanced symbol
((A+B) + (C-D) No One closing brace is missing.
((A+B) + [C-D]) Yes Opening and closing braces correspond
((A+B) + [C-D]] No The last brace does not correspond with the first opening brace.

For tracing the algorithm let us assume that the input is () (() [()])

Input Symbol Operation Stack Output
( Push ( (
) Pop (
Test if ( and A[i] match? YES
( Push ( (
( Push ( ( (
) Pop (
Test if ( and A[i] match? YES
(
[ Push [ ( [
( Push ( ( [ (
) Pop )
Test if ( and A[i] match? YES
( [
] Pop [
Test if [ and A[i] match? YES
(
) Pop (
Test if ( and A[i] match? YES
Test if Stack is Empty? YES TRUE
Exit mobile version