Valid Parentheses
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Stack.
Valid Parentheses
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.
Visual Representation
s = "{ [ ] }"
Step 1: '{' -> Push to Stack. Stack: ['{']
Step 2: '[' -> Push to Stack. Stack: ['{', '[']
Step 3: ']' -> Matches Top '['. Pop. Stack: ['{']
Step 4: '}' -> Matches Top '{'. Pop. Stack: []
Result: Valid (Stack is Empty)Examples
Input: s = "()[]{}"
Output: true
Approach 1
Level I: Brute Force (String Replace)
Intuition
Regular expressions or string replacements can continuously remove valid adjacent pairs
(), {}, [] until the string is empty or no more replacements can be made.⏱ O(N^2) where N is the length of the string, as `replace` scans the string multiple times.💾 O(N) for string copies during replacement.
Approach 2
Level II: Recursive (Function Call Stack)
Intuition
Instead of an explicit stack object, we can use recursion. Each function call 'expects' a specific closing bracket. If it finds one, it returns; if it finds another opening bracket, it recurses. This demonstrates how the computer's memory uses a stack internally.
⏱ O(N)💾 O(N) due to recursion depth.
Approach 3
Level III: Optimal (Stack Mapping)
Intuition
Iterate through the string. If we see an opening bracket, push its corresponding closing bracket onto the stack. If we see a closing bracket, check if it matches the top of the stack. This simplifies the logic by storing what we expect next.
⏱ O(N)💾 O(N)
Detailed Dry Run
| Char | Action | Stack Status | Match? |
|---|---|---|---|
| '(' | Push ')' | [')'] | - |
| '[' | Push ']' | [')', ']'] | - |
| ']' | Pop | [')'] | Yes |
| ')' | Pop | [] | Yes |
⚠️ Common Pitfalls & Tips
Be careful with strings that only contain opening brackets, or strings where the stack becomes empty too early.
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.