This is LeetCode #20: Valid Parentheses — the #1 most asked stack problem! 🏗️
💡 Think of it like this: Imagine you're checking if all the doors in a building are properly closed. Every opening bracket ( [ { is like opening a door, and every closing bracket ) ] } is like closing one. They must match in the right order!
Why a Stack? The last door you opened must be the first one you close. That's exactly what a stack does — Last In, First Out (LIFO)!
The Algorithm:
💭 Challenge time! Now implement this yourself using the strategy above. The best way to learn is by doing! ⭐
Trace for '({[]})':
Complexity: Time O(n) — one pass. Space O(n) — stack can hold n/2 opening brackets.
def isValid(s):
stack = []
match = {')': '(', ']': '[', '}': '{'}
for char in s:
if char in match: # Closing bracket
if stack and stack[-1] == match[char]:
stack.pop() # Match found!
else:
return False # Mismatch!
else:
stack.append(char) # Opening bracket → push
return len(stack) == 0 # Empty stack = all matched!
is_valid("()")
True
is_valid("()[]{}")
True
is_valid("{[]}")
False