edubun
English
1 / 19

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 questions

You will learn

  • Use push, pop and peek on a stack
  • Check brackets with a stack

Before this: Arrays

1Explore

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);          // 2
Output
5
8
2

6Problem

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.

  1. C
  2. A
  3. B
Hint

C went in last.

Solution

Answer:

  1. C
  2. B
  3. 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.

{[()()]}
Stack (top on the right)

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.

([)]
Stack (top on the right)

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.

(()
Stack (top on the right)

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.

  1. function line() {
  2. return "-";
  3. }
  4. function draw() {
  5. const a = line();
  6. return a + a;
  7. }
  8. function main() {
  9. const pic = draw();
  10. console.log(pic);
  11. }
  12. main();
Variables
Output
--

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.

Expected output
kcats
Your code
const 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.

Expected output
true
false
false
Your code
function 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());
Error message
TypeError: Cannot read properties of undefined (reading 'toUpperCase') (line 3)
  1. The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
  2. After the colon: what went wrong, usually with the name involved.
  3. 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.

Mistake
const st = [4, 8, 5];
console.log(st[0]);
Output
4
Fixed
const st = [4, 8, 5];
console.log(st[st.length - 1]);
Output
5

When 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.

Next unitQueues
Full text · The whole lesson as one text

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. Many stacks also offer peek, which looks at the top without removing it.

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);          // 2
A stack drawn as a pile. Push and pop work only at the top. Choose a bracket string and press Check brackets to watch a stack decide whether it is balanced.

Checking 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. At the end the stack must be empty, or some opener was never closed.

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.

Where else stacks appear

  • The call stack. When function a calls b and b calls c, the computer pushes a record for each call. When c returns, its record is popped and b continues where it stopped. Infinite recursion fills this stack, which is the "stack overflow" error.
  • Undo. An editor pushes each change. Undo pops the most recent change and reverses it.
  • Back button. A browser pushes each page you leave; Back pops the last one.
  • Depth-first search. The algorithms course used a stack to go as deep as possible in a maze before backing up.
BackgroundThe stack as a computing idea is usually traced to Friedrich L. Bauer and Klaus Samelson in Munich. Working on how to translate arithmetic formulas, they kept postponed operations in a store where the last item put in is the first taken out, and they called it the Keller, German for cellar. They applied for a patent on the method in 1957; it was granted in the United States in 1962. At about the same time, list processing by Allen Newell, Cliff Shaw and Herbert Simon at the RAND Corporation also relied on stacks, because their programs were full of recursion.

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. Peek would read the top value without shortening the stack, so it does not change the next value that pop would return.

The bracket exercise counts pushes and pops, not every action performed by a program. Checking whether a closing bracket matches the top is a separate test, and reading a character also takes work. Use the trace to explain the result before comparing operation counts. A string may finish with equal numbers of opening and closing brackets yet still fail because their types close in the wrong order, as in ([)]. Successful checking needs both correct nesting throughout the scan and an empty stack at the end.

Key points
  • 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.

Practice questions from Stacks on edubun

Embed this quiz

Free to embed. Please keep the credit line.

Sources for this course (11)
  • MIT OpenCourseWare 6.006 Introduction to Algorithms, Spring 2020 (Demaine, Ku, Solomon)
  • lecture notes 2 Data Structures (interface vs data structure, Sequence and Set interfaces, stack = insert_last/delete_last, queue = insert_last/delete_first, array, linked list, dynamic array, amortized Θ(1) append)
  • 4 Hashing (chaining, pigeonhole collisions, chain length n/m)
  • 6 Binary Trees Part 1 (height, traversal order, O(h) operations) and 7 Binary Trees Part 2: AVL (Adelson-Velsky and Landis, 1962) at ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/pages/lecture-notes
  • MDN Web Docs, Array.prototype.shift (shifts all values left by 1)
  • Array.prototype.unshift, Map (insertion order, Map vs Object, spec requires sublinear average access) and Set (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects)
  • ECMAScript 2025 Language Specification (tc39.es/ecma262)
  • 24.1 Map Objects and 24.2 Set Objects ("must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements")
  • Array.prototype.shift steps (Repeat, while k < len: move element k to k - 1)
  • D. E. Knuth, The Art of Computer Programming vol. 3 (2nd ed. 1998) section 6.4 History (H. P. Luhn, IBM internal memorandum January 1953, hashing with chaining; digit pairs added mod 10, 31415926 -> 4548) via gwern.net copy, and IEEE Spectrum, "Hans Peter Luhn and the Birth of the Hashing Algorithm" (2018)
  • "A brief history of the stack", SIGCIS (sigcis.org/files/A brief history.pdf: Bauer and Samelson applied for the patent in 1957, US 3,047,228 granted July 31, 1962; IPL list processing by Newell, Simon and Shaw at RAND 1956) and Wikipedia, Information Processing Language (Newell, Shaw, Simon, RAND and Carnegie Institute of Technology, about 1956).

Checked: 2026-10-18