Lesson 13 of 19
Stacks
Undo works like a stack of edits. Push adds an edit to the top. Pop takes the most recent edit off first.
The newest open task closes first
Last in, first out (LIFO) fits jobs that nest inside each other. To check brackets, push each opening bracket. Each closing bracket must match the opening bracket on top. An empty stack at the end tells you that every opening bracket was closed, provided each match succeeded.
Work through an example
Read the four characters in ([)]. At which character can a bracket checker first tell something is wrong?
Step-by-step solution
- Read ( and then [. Push both opening brackets. The top now holds [.
- The third character is ). It needs ( on top, but the most recent opening bracket is [.
- Stop at the third character. Counting two openings and two closings would miss the ordering error.
JavaScript example
function balanced(text) {
const stack = [];
const opener = { ")": "(", "]": "[" };
for (const ch of text) {
if (ch === "(" || ch === "[") stack.push(ch);
else if (ch in opener && stack.pop() !== opener[ch]) return false;
}
return stack.length === 0;
}
balanced("([)]"); // falseDSA compiler
Try it yourself
Finish the animation to unlock this question.
Push A, push B, then pop twice. What comes out?
Play Pancake Stack · Related exercise · Stack · See this stage of the beginner path