(empty)
stack
A bracket string is valid when every opener is closed by the correct closer in the right order. A stack makes this a single linear scan: push openers, pop and verify on every closer.
Given a string s containing only ( ) [ ] { }, return true if every opening bracket is closed by the same type in the correct order, false otherwise. "([{}])" → true. "([)]" → false (crossed nesting). "{[]}" → true.
) → (, ] → [, } → {.false.stack.length === 0. A non-empty stack means unmatched openers were never closed."(" never triggers a mismatch during the loop — only the trailing length check catches the unclosed opener.Stack space is O(n) in the worst case (e.g. "(((((") but never more than that.
"([{}])" — push opening brackets, match closing brackets against the stack.function isValid(s: string): boolean {
const stack: string[] = [];
const match: Record<string, string> = { ')': '(', ']': '[', '}': '{' };
for (const ch of s) {
if (ch === '(' || ch === '[' || ch === '{') {
stack.push(ch); // push opener
} else {
if (stack.pop() !== match[ch]) // pop & verify closer
return false;
}
}
return stack.length === 0; // unmatched openers?
}stack holds unmatched openers; match is a O(1) lookup from closer to its expected opener.stack.pop() removes the top and returns it (or undefinedif empty). If it doesn't equal the required opener, the bracket is unmatched or crossed — return false immediately.true — which is correct per the problem definition."([)]" from valid input.match map and the opener check. The algorithm is O(1) per bracket type.| matching/nesting order matters | stack (LIFO) |
| closing bracket must pair with most-recent opener | push opener, pop on close |
| detect unclosed openers | stack.length === 0 at end |
| "balanced brackets" variant | same push/pop skeleton ± augmentation |
function isValid(s: string): boolean {
const stack: string[] = [];
const match: Record<string, string> = { ')': '(', ']': '[', '}': '{' };
for (const ch of s) {
if (ch === '(' || ch === '[' || ch === '{') {
stack.push(ch);
} else {
if (stack.pop() !== match[ch]) return false;
}
}
return stack.length === 0;
}"([)]" return?"((" — which check catches the error?stack.pop() on an empty stack in JavaScript returns undefined. How does the solution handle this?