Stack
Easy
Valid Parentheses
Determine if the input string has valid matching brackets.
10 min read
Solve on LeetCodeProblem Understanding
Given a string s containing just the characters (, ), {, }, [ and ], determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Example:
- Input:
s = "()[]{}"-> Output:true - Input:
s = "(]"-> Output:false - Input:
s = "([)]"-> Output:false
Algorithm Strategy
We use a Stack data structure.
- Iterate through the string char by char.
- If we see an open bracket (
(,{,[), push it onto the stack. - If we see a close bracket (
),},]), check the top of the stack:- If stack is empty, it's invalid (no matching open).
- If stack top is the matching open bracket, pop the stack.
- Otherwise, it's a mismatch -> invalid.
- At the end, stack must be empty (all opened brackets were closed).
Interactive Visualization
Step 1 / 1
Empty Stack
Top Index: -1Initializing...
1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.ON THIS PAGE
- Problem Understanding
- Algorithm Strategy
- Interactive Visualization
- Dry Run
- Edge Cases & Common Mistakes
- Solution
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
