Valid Parentheses Check
Validate nested brackets with a Python stack. Students push openers, match the latest one first, and reject early closers or openings left at the end.
1# Take string2s = input("Enter string with parentheses: ")34# Check balance5stack = []6valid = True7for char in s:8 if char in '([{':9 stack.append(char)10 elif char in ')]}':11 if not stack:12 valid = False13 break14 top = stack.pop()15 if (char == ')' and top != '(') or (char == ']' and top != '[') or (char == '}' and top != '{'):16 valid = False17 break1819if stack:20 valid = False2122print("Valid" if valid else "Invalid")
Output
Enter string with parentheses: ()[]{}
ValidIn this one
- Use last-in-first-out matching
- Reject mismatched closers
- Check leftover openers
How it works
- 1
Push opening brackets onto stack.
- 2
For a closer, require and pop a matching latest opener.
- 3
Reject any leftover stack entries at the end.
Walk through Valid Parentheses Check
Text: ([)]
- 1.Push (, then push [; the latest opener is [.
- 2.The next character ) pops [ but requires (.
- 3.The mismatch sets valid false and ends the scan.
Edge cases
Does ([)] pass?
Does ([)] pass?
No. Its nesting order is wrong.
What happens for an extra closing bracket?
What happens for an extra closing bracket?
An empty stack triggers invalid before pop.
What's going on
The stack stores unfinished opening brackets. A closing bracket must match the most recently stored opener, which is removed with pop.
This last-in-first-out rule enforces nesting, not just equal counts. ([)] fails because ) encounters [. At the end, any remaining opener makes the input invalid. Nonbracket characters are ignored. Empty input has no mismatches or leftovers and is accepted.
Does ([)] pass? No. Its nesting order is wrong.
What happens for an extra closing bracket? An empty stack triggers invalid before pop.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why use a stack?
Pick an answer to check it.
Question 2
Does ([)] pass?
Pick an answer to check it.
Questions people ask
Does ([)] pass?
No. Its nesting order is wrong.
What happens for an extra closing bracket?
An empty stack triggers invalid before pop.
Why use a stack?
The latest opener must close first.
๐Related Content
- ๐
Phase 5 - Learn Concepts
Review Phase 5 concepts and explanations
- ๐
Phase 5 - Quiz
Test your Phase 5 understanding with quiz questions
- ๐ป
Phase 5 - All Practice Problems
Explore all practice problems for Phase 5
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum