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
UnverifiedTime 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
- On an opener, push the closer you expect. A closer that is not the top, or an empty stack, is false.
([)]catches a bad order.(()catches a missing close. Is the stack empty at the end?- The empty string is true. One character is false.