Easy
Valid Parentheses
👶 The 5-Year-Old Summary
You have a bunch of brackets like ()[]{}. Does every opening bracket have its matching closing bracket that properly nests inside? Like properly stacking and unstacking plates!
🎮 Interactive Visualizer
Click "Step" to see the stack in action!
Stack (plates):
🧠 The Brain Hack
When brackets need to "match" or "nest," think STACK! Opening bracket → push to stack. Closing bracket → pop and check if it matches!
💻 The Clean Solution
def is_valid(s):
# A stack to hold opening brackets
stack = []
# Matching pairs
mapping = {')': '(', '}': '{', ']': '['}
for char in s:
# If it's a closing bracket
if char in mapping:
# Pop from stack (or use placeholder if empty)
top = stack.pop() if stack else '#'
# Does it match?
if mapping[char] != top:
return False
else:
# It's an opening bracket - push to stack
stack.append(char)
# Valid if stack is empty (all matched)
return len(stack) == 0
# Try it!
print(is_valid("([])")) # True
print(is_valid("([)]")) # False
Time: O(n) - one pass through the string
Space: O(n) - worst case, all opening brackets