1. Open-bracket stack
Push opens; the most recent must match the next close.
const stack = []Typorithm · easy
Step 1 of 8 · intro card
Stacks & Queues
Push openers on a stack; each closer must match the most recent opener, and the stack must end empty.
Brackets nest, so the last opened must be the first closed — classic LIFO.
A stack holds open brackets; each closer pops and checks against its required opener.
A mismatch or a leftover opener at the end means the string is invalid.
Push openers, pop on closers.
Top opener must match the closer.
End with an empty stack.
function isValid(s) {
const stack = [];
const pairs = { ")": "(", "]": "[", "}": "{" };
for (const ch of s) {
if (ch === "(" || ch === "[" || ch === "{") {
stack.push(ch);
} else if (stack.pop() !== pairs[ch]) {
return false;
}
}
return stack.length === 0;
}Connect each part of the code to the concept before you type.
Push opens; the most recent must match the next close.
const stack = []Map each closing bracket to its required opener.
const pairs = { ")": "(", "]": "[", "}": "{" }Remember every opening bracket on the stack.
stack.push(ch)The top opener must match the current closer.
stack.pop() !== pairs[ch]An empty stack means every bracket was matched.
return stack.length === 0Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.