🔥 Today's Challenge Problem: Given a string containing just (, ), {, }, [ and ], determine if the input string is valid.
Example:
Input: "()[]{}"
Output: true
🧠 The Hunter's Strategy Weapon of Choice: Stack Data Structure When dealing with nested structures, stacks are your best friend. Here's why:
Last-In-First-Out (LIFO) principle perfectly matches bracket validation
O(n) time complexity - we process each character exactly once
Early termination possible when mismatches occur
Approach Breakdown: Initialize an empty stack
Create a bracket pairing map (] → [, etc.)
Iterate through the string:
Push opening brackets onto stack
For closing brackets: check if top of stack matches
Final stack check ensures all brackets were closed
💻 TypeScript Implementation
function isValid(s: string): boolean {
const stack: string[] = [];
const bracketPairs: Record = {
')': '(',
'}': '{',
']': '['
};
for (const char of s) {
if (!bracketPairs[char]) {
stack.push(char);
} else if (stack.pop() !== bracketPairs[char]) {
return false;
}
}
return stack.length === 0;
}
Key Optimizations:
Used a hashmap for O(1) bracket lookups
Early return on mismatch
Single pass through the string
🎯 Edge Cases That Made Me Wiser Empty string: Technically valid (handled by final stack check)
Nested valid brackets: ({[]}) → true
Mismatched brackets: ([)] → false
Single bracket: [ → false
🚀 Performance Analysis Metric Value Time Complexity O(n) Space Complexity O(n) LeetCode Runtime 72ms (faster than 92.5%) 💡 Pro Tips Visualize the stack like a tower - you can only remove the top block!
Test these cases:
"(([]){})" (complex but valid)
"]" (immediate fail)
Try solving it without stack (hint: recursive approach exists)
What's your favorite stack-based algorithm? Let's discuss in the comments! 👇
Tomorrow's Preview: We'll tackle "Merge Two Sorted Lists" using pointer manipulation!