Stack
Think of a stack of plates. You only ever touch the top one, and the last plate you put down is the first one you pick up.
2 · Watch
No sound? Captions are on by default.
3 · Now you drive
Keys:←→ stepSpace playR reset
Valid Parentheses
or try
Up to 12 brackets: ( ) [ ] { }. Anything else is ignored.Start with an empty stack.Step 1 of 8. Starting out. 6 brackets to read. The stack is empty.
Step 1 of 8
solution.ts▶ marks the line running now
function isValid(s: string): boolean {
const stack: string[] = [];
const pairs: Record<string, string> = { ")": "(", "]": "[", "}": "{" };
for (const ch of s) {
if (!(ch in pairs)) {
stack.push(ch);
} else if (stack.pop() !== pairs[ch]) {
return false;
}
}
return stack.length === 0;
}
4 · Your turn
0 of 1 problems solved
- Easy01
Valid Parentheses
The one you just watched. Write it from memory.