This Python script demonstrates the use of the Stack data structure to check balanced parentheses, brackets, and braces in an expression.
Itβs a classic Data Structures & Algorithms (DSA) problem used in programming, interviews, and real-world parsing tasks.
- β Implements a custom Stack class in Python
- β Checks for balanced parentheses, brackets, and braces
- β Handles nested and complex expressions
- β Supports expressions with other characters (letters, numbers, operators)
- β Easy to extend for other parsing problems
Python 3.x
No additional libraries are required as the implementation uses core Python.
-
Stack Implementation
push(item)β Adds element to toppop()β Removes and returns top elementpeek()β Returns top element without removingis_empty()β Checks if stack is empty
-
Balanced Parentheses Algorithm
- Traverse each character of the expression
- Push opening symbols
(,[,{onto the stack - On closing symbols
),],}, check if the top of the stack matches - If mismatch or leftover elements β expression is not balanced
- Otherwise β balanced
print(is_balanced("()")) # True
print(is_balanced("([)]")) # False
print(is_balanced("((()))[{}]")) # True
print(is_balanced("((()))[{}]]")) # False
print(is_balanced("a + (b * c) - {d / [e + f]}")) # True
print(is_balanced("((a + b) * (c - d)")) # False-
Time Complexity: O(n) β n = length of expression
-
Space Complexity: O(n) β Worst-case stack size (all opening symbols)
- Core DSA concept: Stack
- Common in parsing, compiler design, expression evaluation
- Often asked in technical interviews
- Foundation for more advanced algorithms like infix-to-postfix conversion
- Add support for custom symbols
- Integrate into expression evaluators or mini calculators
- Visualize stack operations for educational purposes
- Combine with queues or trees for complex parsing algorithms