2 / 7 · Intermediate
Stacks
Checking that the brackets in {[()()]} pair up correctly takes one stack and 8 pushes and pops, one for each bracket.
Jump to the 10 practice questions1Explore
Last in, first out
Think of a pile of plates. You put a clean plate on top, and when you need one you take it from the top. The plate you added last is the first one out. A stack is a data structure with exactly that rule, called last in, first out (LIFO). It offers two main operations: push puts a value on top, and pop removes the value on top and gives it back.
Push a few values, then pop. The value that comes out is always the one on top, the last one pushed.
Press a button: each one runs one operation and shows what it cost.
[]Total steps 0
2Problem
The order out
A stack gives back values in which order?
Hint
Plates: you take the one you put down last.
Solution
Answer: Last in, first out
The value pushed last sits on top and is popped first (LIFO).
3Problem
What is on top?
Start empty. Push 4, push 8, push 5, pop, push 2. What is on top?
Hint
After the pop the stack is 4, 8.
Solution
Answer: 2
After the pop the stack is 4, 8; pushing 2 puts it on top.
4Problem
How many are left?
After those operations, how many values are on the stack?
Hint
Four pushes, one pop.
Solution
Answer: 3
Four pushes and one pop leave 4 − 1 = 3 values: 4, 8, 2.
5Explain
A stack in a JavaScript array
In MIT's 6.006 notes the stack is a special case of the sequence interface: insert last(x) and delete last(). That already tells you how to build one. Put the values in a dynamic array and treat the end of the array as the top. In the last unit the end was the cheap end, so push and pop each cost 1 step (amortized, because of the occasional copy). The size of the stack makes no difference. Popping from a stack of 3 values or of 3 million values is the same single step.
const stack = [];
stack.push(4);
stack.push(8);
stack.push(5);
console.log(stack.pop()); // 5, the last one pushed
console.log(stack[stack.length - 1]); // peek: 8
console.log(stack.length); // 25
8
26Problem
Pop from a big stack
Popping from a stack (stored in a dynamic array) that holds 1,000 values takes how many steps?
Hint
Nothing else moves when the last value is taken.
Solution
Answer: 1
The lab counts removing the final array entry as 1 step; no remaining value shifts. This is the model’s operation count, not a promise that every real runtime takes identical time.
7Problem
Pop until empty
Push A, then B, then C, then pop until empty. Put the popped values in order.
- C
- A
- B
Hint
C went in last.
Solution
Answer:
- C
- B
- A
Last in, first out: C was pushed last, so it comes out first.
8Explore
Balanced brackets
A classic use for a stack is checking that brackets are balanced, which every code editor and compiler does. Read the text from left to right. Each opening bracket, (, [ or {, is pushed. Each closing bracket must match the opener on top of the stack: if it does, pop that opener; if the stack is empty or the top is a different kind, the string is not balanced.
Each opener is pushed; each closer must match the top and pops it.
Read {[()()]} from the left.
9Problem
Pushes and pops
How many pushes and pops in total does checking {[()()]} with the bracket method take?
Hint
Four openers, four closers.
Solution
Answer: 8
Each of the four opening brackets is pushed, and each matching closer pops one: 4 + 4 = 8. This counts pushes and pops, not every comparison or character-reading action.
10Explore
When the order is wrong
Try the strings in the lab. {[()()]} needs 4 pushes and 4 pops, 8 steps, and ends with an empty stack. ([)] fails at the third character: the ) arrives while [ is on top. (() reads to the end with one ( left over. Why does a stack fit this job? Brackets nest, and the most recently opened one must be the first to close. That is last in, first out.
) arrives while [ is on top: the types close in the wrong order.
Read ([)] from the left.
11Problem
Where ([)] fails
Checking ([)] from the left, where does it fail?
Hint
Look at the top when ) arrives.
Solution
Answer: At )
When ) arrives the top is [, which does not pair with ).
12Explore
One opener left over
Every closer matched, but the stack is not empty at the end.
Read (() from the left.
13Problem
What is wrong with (()
What is wrong with (() ?
Hint
Look at the stack at the end.
Solution
Answer: One ( is still on the stack at the end
The ) closes the second (, leaving the first ( unclosed.
14Explain
The call stack
Write a trace with the bottom of the stack on the left and the top on the right. Starting empty, push 4, push 8 and push 5 to get [4, 8, 5]. A pop returns 5 and leaves [4, 8]; pushing 2 gives [4, 8, 2]. Keep the value returned by pop separate from the values still stored.
main calls draw, draw calls line. Each call waits on top of the one that called it, and the top one finishes first.
function line() {return "-";}function draw() {const a = line();return a + a;}function main() {const pic = draw();console.log(pic);}main();
--
15Problem
Top of the call stack
Function main calls draw, and draw calls line. While line runs, which record is on top of the call stack?
Hint
The most recent call.
Solution
Answer: line
The most recent call is on top; when line returns, draw continues.
16Practice
Reverse a word
Use the stack to reverse the word. The program should print kcats.
kcatsconst word = "stack";
const st = [];
for (const ch of word) st.push(ch);
let out = "";
// Pop every letter off st and add it to the end of out.
console.log(out);
Hint
pop takes from the top, which is the last letter pushed.
A solution
const word = "stack";
const st = [];
for (const ch of word) st.push(ch);
let out = "";
while (st.length > 0) out += st.pop();
console.log(out);17Practice
The bracket checker
Finish the bracket checker. It should print true, false, false.
true
false
falsefunction balanced(s) {
const pairs = { ")": "(", "]": "[", "}": "{" };
const st = [];
for (const c of s) {
if ("([{".includes(c)) st.push(c);
// If c is a closing bracket: return false when st is empty
// or when st.pop() is not pairs[c].
}
return st.length === 0;
}
console.log(balanced("([]{})"));
console.log(balanced("([)]"));
console.log(balanced("())("));
Hint
A closer must find its own kind of opener on top.
A solution
function balanced(s) {
const pairs = { ")": "(", "]": "[", "}": "{" };
const st = [];
for (const c of s) {
if ("([{".includes(c)) st.push(c);
else if (st.length === 0 || st.pop() !== pairs[c]) return false;
}
return st.length === 0;
}
console.log(balanced("([]{})"));
console.log(balanced("([)]"));
console.log(balanced("())("));18Explain
Common mistakes
const st = [];
const top = st.pop();
console.log(top.toUpperCase());TypeError: Cannot read properties of undefined (reading 'toUpperCase') (line 3)
- The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
- After the colon: what went wrong, usually with the name involved.
- The line number shows where the program stopped. A SyntaxError stops it before any line runs.
pop on an empty stack gives undefined, not an error, so the mistake shows up one line later. Check st.length first.
const st = [4, 8, 5];
console.log(st[0]);4const st = [4, 8, 5];
console.log(st[st.length - 1]);5When the end of the array is the top, peek reads the last value, not the first.
19
Summary
- A stack is last in, first out: push on top, pop from the top.
- Built on the end of a dynamic array, push and pop are 1 step each.
- Bracket checking pushes openers and pops on each closer; {[()()]} takes 8 steps.
- The call stack, undo and the Back button are stacks.