Valid Parentheses
LeetCode 20 · Easy · solution, intuition & step-by-step walkthrough
Push openers; each closer must match the top.
This is how I solved Valid Parentheses (LeetCode 20), an easy problem from the Parentheses / Bracket Matching pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Every closing bracket must match the most recent unmatched opening bracket — that's last-in-first-out, a stack.
Approach
- 1
Opening bracket → push.
- 2
Closing bracket → pop and check it matches; empty stack → invalid.
- 3
Valid only if the stack is empty at the end.
How I solved it
Stack matchingPythonO(n) time · O(n) space
class Solution:
def isValid(self, s: str) -> bool:
stack = []
mpp={
"(":")",
"{":"}",
"[":"]"
}
stack = []
for char in s:
if char in mpp:
stack.append(char)
else:
closing_brace = char
if stack:
opening_brace = stack.pop()
if mpp[opening_brace]!=closing_brace:
return False
else:
return False
return True if len(stack)==0 else FalseValid Parentheses — FAQ
What is the intuition behind Valid Parentheses?
Every closing bracket must match the most recent unmatched opening bracket — that's last-in-first-out, a stack.
How do you solve Valid Parentheses (LeetCode 20)?
1. Opening bracket → push. 2. Closing bracket → pop and check it matches; empty stack → invalid. 3. Valid only if the stack is empty at the end.
What is the time and space complexity of Valid Parentheses?
Time: O(n). Space: O(n). (Accepted approach: Stack matching.)
What are common mistakes in Valid Parentheses?
Leftover openers like '((' make it invalid.