Valid Parentheses
Valid Parentheses
Section titled “Valid Parentheses”
Easy
Day 12 • Striver Blind 75
📌 Problem Overview
Section titled “📌 Problem Overview”Given a string s containing just the characters (, ), {, }, [ and ], determine if the input string is valid.
Examples & Constraints
Section titled “Examples & Constraints”Example 1:
- Input:
s = "()" - Output:
true
Example 2:
- Input:
s = "()[]{}" - Output:
true
Example 3:
- Input:
s = "(]" - Output:
false
Example 4:
- Input:
s = "([)]" - Output:
false
Example 5:
- Input:
s = "{[]}" - Output:
true
Constraints:
1 ≤ s.length ≤ 10⁴
💡 Approach & Intuition
Section titled “💡 Approach & Intuition”Tests your understanding of the stack data structure and its LIFO property.
🎯 Pattern Recognition
Section titled “🎯 Pattern Recognition”Pattern: Stack for Matching
Use a stack to match paired elements in nested structures.
📊 Step-by-Step Execution (Mermaid Diagram)
Section titled “📊 Step-by-Step Execution (Mermaid Diagram)”graph TD Start["Input Data"] --> Process["Process Element by Element"] Process --> Lookup{"Hash Map / Set Lookup"} Lookup -- "Match Found" --> Return["Return Indices / Result"] Lookup -- "No Match" --> Store["Store in Map / Set"] Store --> Process🐢 Brute Force Solution
Section titled “🐢 Brute Force Solution”// Stack is the standard approach- Time Complexity:
O(n) - Space Complexity:
O(n) - Explanation: Use a stack with a hash map for bracket matching.
⚡ Optimized Solution
Section titled “⚡ Optimized Solution”function isValid(s) { const stack = []; const pairs = { ')': '(', '}': '{', ']': '[' }; for (const char of s) { if (!pairs[char]) { stack.push(char); } else { if (stack.pop() !== pairs[char]) return false; } } return stack.length === 0;}- Time Complexity:
O(n) - Space Complexity:
O(n) - Explanation: Push opening brackets, pop and match on closing brackets.
🐾 Step-by-Step Walkthrough
Section titled “🐾 Step-by-Step Walkthrough”- Initialize State: Setup necessary pointers, dynamic programming arrays, or hash maps.
- Iterate & Evaluate: Process the input according to the boundary conditions.
- Update & Return: Compute the optimal answer and return early or at termination.
🎙️ FAANG Interview Pitch
Section titled “🎙️ FAANG Interview Pitch”- Recognize as a stack problem
- Use LIFO property for nesting
- Use a hash map for bracket pairs
💡 Progressive Hints
Section titled “💡 Progressive Hints”- Use a stack to track opening brackets.
- When you see a closing bracket, check if it matches the top of the stack.
- Use a hash map to pair brackets.