Push and pop at one end, see a stack on an array and on a linked list, follow the call stack, and build your own stack.
An engineering platform's config editor lets engineers change deployment settings. You are adding an Undo button to it.
Every edit goes onto a pile. Undo takes back the newest edit. Press it again and it takes back the one before.
The editor never needs the oldest edit first, and it never needs edit number 7 on its own. It needs the newest edit that is still there.
Any array or list could hold that pile. What matters is the rule for using it: add at one end, and remove from the same end. That rule is called a stack.
Think of plates in a canteen. A clean plate goes on top of the pile. When someone needs a plate, they take the top one. Nobody pulls a plate out of the middle, and the plate at the bottom is used last.
To reach the fifth plate down, you must lift off the four above it first. In a stack, the plates are values, and only the top plate can be touched.
A pile of plates: new plates go on top, and the top plate is the first one taken. The last in is the first out.
A stack is a rule about how you use storage. It is not a new kind of memory. It can sit on an array: the values lie side by side, the bottom at index 0, and a number called top marks where the stack ends. Or it can sit on a linked list: each value is a node, and the head is the top.
Step through the picture below. Watch what moves when you push and pop, and what never moves.
Step by step: A stack on an array and on a linked list. The animated player loads in your browser.
So a stack is a collection where you add and remove at one end only. Five words appear in every stack problem:
Predict what happens
Q You push 4, then 9, then 2 onto an empty stack. Then you pop once. Which value comes off?
Answer: C
A stack is last in, first out. The newest value, 2, sits on top, so pop returns it. The 4 stays at the bottom until every value above it has been popped.
Every stack operation works at the top. That is the whole design. Nothing else is touched, so the cost does not depend on how tall the stack is.
We count the work in steps. A step is a cell written, a pointer changed, a value copied or an item looked at.
Push puts a value on top. In an array-backed stack, write it into the next free cell, then move top up by one. In a list-backed stack, make a node, point it at the old top, then move head to the new node.
Push: write the value into the next free cell, then move top up. One step, however tall the stack is.
Step by step: Push 25 onto an array-backed stack. The animated player loads in your browser.
What if the array has no free cell? An array has a fixed size. When it is full, the stack makes a new block twice as big and copies every value across.
Then it writes the new value. That push costs one step for each value copied, so it is the slow one.
It is also rare. After a copy to 8 cells, the next 3 pushes are cheap again. Spread over many pushes, the average is still O(1).
A full array grows by copying every value into a block twice as big. That push is slow, but it is rare.
Step by step: Push 8 onto a full array. The animated player loads in your browser.
Predict what happens
Q An array-backed stack has 8 cells and all 8 are in use. The next push copies the values to a block of 16 cells and then writes the new value. How many steps is that push?
Answer: C
The copy touches each of the 8 old values once, and the write touches one cell. The 8 empty cells in the new block cost nothing until they are used.
Pop removes the top value and hands it back. In an array it moves top down by one cell. In a list it moves head to the next node. Peek reads the top and changes nothing.
Both need a top to exist. On an empty stack there is nothing to remove or read, so check first, or decide in advance what to return.
Pop: remove the top value and hand it back. In an array, top moves down one cell. Only the newest leaves.
Step by step: Pop the top of a stack. The animated player loads in your browser.
Predict what happens
Q A stack holds 6, 1, 8 from bottom to top. You run push 5, then pop, then pop. What is on top now?
Answer: B
Push 5 gives 6, 1, 8, 5. The first pop removes 5 and the second removes 8. That leaves 6, 1, with 1 on top.
Exercise · Predict the output: What is on top of the history?. The editor keeps its edits on a stack. This code pushes four edits and then undoes and edits some more. What does it print?
history = []
for edit in ["font", "title", "width", "colour"]:
history.append(edit)
history.pop()
history.append("margin")
history.pop()
history.pop()
print(history[-1], len(history))A stack is not built for searching. To find a value, look at the top, then the item under it, and keep going down. The deeper the value, the more looks. The same is true of reading the item at any depth: you must get past everything above it.
Step by step: Peek, then search from the top. The animated player loads in your browser.
Exercise · Put it in order: How deep is a value?. Arrange the lines into a function that says how many items sit above the first match, searching from the top down. The stack is given bottom first. It returns -1 when the value is not there.
def depth_of(stack, target):
steps = 0
for i in range(len(stack) - 1, -1, -1):
if stack[i] == target:
return steps
steps += 1
return -1
for i in range(len(stack)):Every program has a stack that you never wrote. When a function calls another function, the computer pushes a frame onto the call stack. The frame holds the call's arguments and the place to return to. When the function returns, its frame is popped.
Recursion is the call stack at work. fact(4) calls fact(3), which calls fact(2). Each call waits underneath until the one above it returns, so the last call made is the first to finish.
The call stack: each function call pushes a frame, and each return pops one. Recursion is a stack at work.
Step by step: factorial(4) on the call stack. The animated player loads in your browser.
The call stack has a fixed size. A recursion that never reaches its base case keeps pushing frames until there is no room left. The program then stops with a stack overflow error. Every recursion needs a base case that stops it.
Step by step: Recursion with no base case. The animated player loads in your browser.
Predict what happens
Q fact(5) calls fact(4), and so on down to fact(1), which returns at once. At the deepest point, how many frames are on the call stack?
Answer: C
Each call stays on the stack until it returns. fact(1) returns first, then fact(2) and so on. At the deepest point all five calls are on the stack.
Here is every operation side by side. The array column has one footnote: a push that finds the array full costs O(n). The rows below the top show where a stack is weak.
| Operation | Array-backed stack | List-backed stack | What sets the cost |
|---|---|---|---|
| Push | O(1) on average; O(n) for the one push that grows a full array | O(1): a new node and two pointer changes | Only the top is touched |
| Pop | O(1): top moves down one cell | O(1): head moves to the next node | Only the top is touched |
| Peek (read the top) | O(1) | O(1) | One read |
| Search for a value | O(n): look from the top down | O(n): walk from the head down | A stack has no index and no order to use |
| Read any item below the top | O(k) for the item k places down | O(k) | You must get past k items first |
| Memory for each value | One cell, plus some spare room | One node: the value and a pointer | The list pays for a pointer each |
Both ways of storing a stack give the same costs for the operations a stack is made for. The array is faster in practice, because its values sit side by side. The list never has to grow a block and copy it.
Now drive the stack yourself. Type a value, then push, pop, peek or search, and watch each operation run step by step. The step counter shows the cost. The panel below it shows what the same operation costs when the stack is stored the other way.
Try these five, in order:
The sandbox: build a list and run its operations step by step. It loads in your browser.
Now write the structure yourself. The lab gives you a Stack class with a block of 4 cells and a top number. You write five methods: push, pop, peek, size and is_empty. The sixth, to_list, is already written, so the tests can look inside your stack.
The part to take care over is push. The block has 4 cells, and the tests push more than 4 values. When the block is full, make a new block twice as big, copy the values across, then write the new value.
Each test creates a new, empty stack, calls your methods in order and compares every value they return. When a test fails, the result names the exact call that went wrong, the value it returned and the value it should return.
Three rules keep the stack correct after every method:
top is the number of cells in use, so it is also the index of the next free cell.pop moves top down before it reads, because the top value sits at index top - 1.-1 from pop and peek, and never crashes.Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
Use a stack when the newest unfinished thing must be dealt with first, and older things can wait. An undo history works this way: the last edit is the first to be taken back. So does a browser's back button, with the pages you visited on a stack.
Stacks also match nested things. When you read ({[]}), each closing bracket must match the most recent opening bracket that is still open. A stack of open brackets answers that in one pass.
Exercise · Find the bug: The bracket check that says yes too soon. This function should say whether every ( has a matching ). It answers True for some texts that are not balanced. Which line is wrong?
def is_balanced(text):
stack = []
for ch in text:
if ch == "(":
stack.append(ch)
elif ch == ")":
if not stack:
return False
stack.pop()
return TrueChoose a queue when the oldest item must go first, as in a line of jobs waiting for a worker. Choose an array when you read by index or search a sorted list. Choose a hash map when you look values up by key.
A stack gives you the newest item and nothing else. Every other item is out of reach until the ones above it are gone.
stack.pop() on an empty Python list raises IndexError: pop from empty list. Java's Stack throws EmptyStackException. The crash usually comes from a bracket matcher that sees a closing bracket first, as in ")(".
Check if stack: before you pop, or return a value that means "empty", as the lab does with -1.
The classic mistake: popping an empty stack. There is no top to remove, so check that the stack is not empty first.
Exercise · Break it: Find the input that undoes too much. An edit history stores each edit in a cell, and a positive number is an edit while 0 is Undo. This function should return how many edits are left. Find an input where it gives the wrong answer.
def edits_left(ops):
cells = [0] * 50
top = 0
for op in ops:
if op > 0:
cells[top] = op
top += 1
else:
top -= 1
return topif stack[-1] == "(" crashes on an empty stack, because there is no last item. The same bug hides in while stack[-1] < x. Write if stack and stack[-1] == "(", so the check for empty comes first.
items.insert(0, x) and items.pop(0) also work as push and pop, but every call shifts all the other values. A loop of n pushes then costs about n^2 / 2 shifts. Keep the top at the end of an array: items.append(x) and items.pop() touch one cell.
In your own stack, return self.cells[self.top] before self.top -= 1 reads the next free cell, not the top value. On a stack holding [3, 8], that returns a stale 0 or an old value instead of 8. Move top down first, then read cells[top].
def depth(n): return 0 if n == 0 else 1 + depth(n - 1) pushes one frame per call. For n = 100,000, Python stops with RecursionError, and other languages overflow the call stack. When the depth can be large, keep your own stack in a loop instead.
Explain the idea in your own words, then take the checkpoint quiz.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · The idea
Q1/2 You push 5, 2, 8 and 1 onto an empty stack, then pop twice. What is on top now?
Answer: B
Pushing gives 5, 2, 8, 1 with 1 on top. The first pop removes 1 and the second removes 8. That leaves 5, 2, with 2 on top.
Q2/2 A stack can be stored on an array or on a linked list. In the linked-list version, what is the top?
Answer: B
Push makes a node and points it at the old head, then moves head to it. Pop moves head to the next node. Both happen at the head, so the head is the top.
Checkpoint · Costs
Q1/4 How many steps does a pop take on an array-backed stack holding 1,000,000 values?
Answer: A
Pop only moves top. No value is copied or moved, so the height does not matter.
Q2/4 An array-backed stack has 4 cells, all in use. The next push makes a block of 8 cells and copies the values. How many steps is that push?
Answer: C
The 4 old values are each copied once, then the new value is written. The 4 spare cells in the new block cost nothing until they are used.
Q3/4 Why is the average push still O(1), even though one push in a while costs O(n)?
Answer: B
After a copy to 2n cells, the next n - 1 pushes need no copy. Spread over all of them, the copy adds only a small constant to each push.
Q4/4 You need to know whether the value 42 is somewhere in a stack. What does that cost?
Answer: C
A stack has no index and no order to use, so a search looks at the items one by one from the top. Only the top is cheap to reach.
Checkpoint · The call stack
Q1/2 What does the computer push onto the call stack when a function is called?
Answer: B
Every call, recursive or not, gets a frame. The frame comes off the stack when the call returns.
Q2/2 A recursive function has no base case. What happens when you call it?
Answer: C
Each call pushes a frame and never returns, so the stack only grows. The call stack has a fixed size, and when it is full the program stops with an error.
Checkpoint · Mistakes and choices
Q1/2 This code checks a closing bracket: if stack[-1] == "(". When does it crash?
Answer: B
Reading the top of an empty stack is an error in every language. Write if stack and stack[-1] == "(", so the check for empty comes first.
Q2/2 Which job is the best fit for a stack?
Answer: B
Undo needs the newest thing first, which is last in, first out. Tickets in arrival order need a queue, a position needs an array, and a lookup by id needs a hash map.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Sandbox and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.