How to Check Balanced Parentheses Using Stack - Simple Guide
To check balanced parentheses using a
stack, push each opening parenthesis onto the stack and pop it when a matching closing parenthesis appears. If the stack is empty at the end and all pairs matched correctly, the parentheses are balanced.Syntax
Use a stack to track opening parentheses. For each character in the string:
- If it is an opening parenthesis like
(, push it onto the stack. - If it is a closing parenthesis like
), pop from the stack and check if it matches the opening one. - If the stack is empty before popping or characters don't match, parentheses are not balanced.
- At the end, if the stack is empty, parentheses are balanced.
python
stack = [] for char in input_string: if char == '(': # opening stack.append(char) elif char == ')': # closing if not stack or stack.pop() != '(': # mismatch or empty return False return len(stack) == 0 # balanced if stack empty
Example
This example shows how to check if parentheses in a string are balanced using a stack. It returns True if balanced, otherwise False.
python
def is_balanced_parentheses(s: str) -> bool: stack = [] for char in s: if char == '(': # opening parenthesis stack.append(char) elif char == ')': # closing parenthesis if not stack or stack.pop() != '(': # no matching opening return False return len(stack) == 0 # Test cases print(is_balanced_parentheses("(())")) # True print(is_balanced_parentheses("(()")) # False print(is_balanced_parentheses("())(")) # False print(is_balanced_parentheses("()()")) # True
Output
True
False
False
True
Common Pitfalls
Common mistakes include:
- Not checking if the stack is empty before popping, which causes errors.
- Ignoring unmatched closing parentheses.
- Only counting parentheses without matching pairs.
- Not verifying the stack is empty at the end, which means some openings were not closed.
python
def wrong_check(s: str) -> bool: stack = [] for char in s: if char == '(': # opening stack.append(char) elif char == ')': # closing stack.pop() # no check if stack empty return True # always returns True, wrong # Correct way includes checks: def correct_check(s: str) -> bool: stack = [] for char in s: if char == '(': # opening stack.append(char) elif char == ')': # closing if not stack or stack.pop() != '(': # check before pop return False return len(stack) == 0
Quick Reference
- Push opening parentheses onto the stack.
- Pop and match when a closing parenthesis appears.
- Return false if mismatch or stack empty when popping.
- Return true only if stack is empty at the end.
Key Takeaways
Use a stack to track opening parentheses and match them with closing ones.
Always check if the stack is empty before popping to avoid errors.
If the stack is empty at the end, parentheses are balanced.
Unmatched closing parentheses or leftover openings mean unbalanced parentheses.
This method works efficiently in a single pass through the string.