Python Program to Check Balanced Parentheses Using a Stack
Intermediate · Data structures
An expression has balanced brackets when every opening bracket, (, [ or {, is closed by the matching kind in the right order, so "{[()]}" is balanced but "(]" and "((a)" are not. A stack is the natural tool: push each opening bracket, and when a closing bracket arrives, the bracket on top of the stack must be its partner.
Program
"(a + b) * [c - d]" is balanced
"{[()()]}" is balanced
"((a + b)" is not balanced
"(a + b]" is not balanced
"a + b)" is not balanced
"" is balancedHow it works
- The stack holds the opening brackets that have not been closed yet, with the most recent one on top.
- Each opening bracket is pushed, and each closing bracket must match the bracket popped from the top of the stack, which
pairslooks up:pairs[")"]is"(". - A closing bracket that arrives when the stack is empty, like the
)in"a + b)", has nothing to close, so the expression is not balanced. - At the end the stack must be empty, and in
"((a + b)"one(is left over, so that one is not balanced either. - Letters and operators are skipped, and the empty string counts as balanced because it has nothing to match.
Other ways to write it
Finding where the problem is
{[()]} -> balanced
(a + b] -> unexpected ] at position 6
((a + b) -> ( at position 0 is never closedStoring each bracket together with its position lets the program say exactly which character is wrong, the way a code editor highlights an unmatched bracket.
By removing pairs
{[()()]} is balanced
{[(])} is not balancedDeleting matched pairs like () over and over leaves an empty string only when the brackets are balanced, which is short to write but slower, and it only works on strings made of brackets alone.
Try it yourself
Add angle brackets < and > as a fourth kind of pair.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises