Easystack-parsing
Valid Parentheses
Problem (restated)
Given a string of brackets, determine if it is valid (correct nesting and order).
Intuition
Push openers; on closer, top must match.
Approaches
Stack matching
Tested onlyTime O(n)Space O(n)
Idea. Stack + map of closing→opening.
Walkthrough. “()[]” true; “(]” false.
Trade-offs. Stack is canonical; counter only works for one type.
Solution
export function isValid(s: string): boolean {
const st: string[] = [];
const pair: Record<string, string> = { ')': '(', ']': '[', '}': '{' };
for (const ch of s) {
if (ch === '(' || ch === '[' || ch === '{') st.push(ch);
else {
if (!st.length || st.pop() !== pair[ch]) return false;
}
}
return st.length === 0;
}
export function isValid(s: string): boolean {
const st: string[] = [];
const pair: Record<string, string> = { ')': '(', ']': '[', '}': '{' };
for (const ch of s) {
if (ch === '(' || ch === '[' || ch === '{') st.push(ch);
else {
if (!st.length || st.pop() !== pair[ch]) return false;
}
}
return st.length === 0;
}
Template connection
Stack parsing matching.
Reflection
- Which pattern gave this away within 90 seconds?
- What changed from the standard template?
- What would break the current solution?