- undo = []
- undo.append("bold")
- undo.append("red")
- undo.append("big")
- last = undo.pop()
- print("undid", last)
- last = undo.pop()
- print("undid", last)
Variables
- undo
- [] (just changed)
Your undo history starts as an empty stack.
You just watched a stack. Each edit went on top, and Ctrl+Z always took the newest one off the top. This rule is called LIFO: last in, first out.
Quick check
Quick check: After those two undos, you type italic and press Ctrl+Z once. What gets undone?
Push, pop, peek, empty#
A stack is a list where you only touch one end, the top. In Python, a plain list is a stack, and its end is the top.
| Operation | Python | Time |
|---|---|---|
| push | stack.append(x) | O(1) |
| pop | stack.pop() | O(1) |
| peek | stack[-1] | O(1) |
| is empty | not stack (an empty list counts as false) | O(1) |
Nothing below the top ever moves, so every operation is O(1). (append is O(1) on average: once in a while the list grows its memory, but spread over all pushes the cost stays constant.)
Quick check
Quick check: stack = [10, 20, 30]. You call stack.pop(), then look at stack[-1]. What do you see?
Popping an empty stack#
[].pop() stops the program with IndexError: pop from empty list. Peeking with [][-1] also raises IndexError. So check first: an empty list counts as false, so if stack: means "the stack has something." Slide n to 0 and watch the guard skip the pop.
n- n = 2
- stack = []
- for i in range(n):
- stack.append(i)
- if stack:
- print("popped", stack.pop())
- else:
- print("empty, nothing to pop")
Variables
- n
- 2 (just changed)
Slide n to 0 to test the empty case.
Play a stack yourself. It starts on [10, 20, 30] and pops once: only 30, the top, leaves.
Checking brackets#
Is "([])" balanced? Three rules with a stack:
- Push every opener.
- On a closer, the stack must not be empty, and the popped opener must match it.
- At the end, the string is valid only if the stack is empty.
Slide case to 1 for ")(": the first ) finds an empty stack. Slide it to 2 for "((": nothing fails, but the stack is not empty at the end.
case- case = 0
- s = ["([])", ")(", "(("][case]
- op = {")": "(", "]": "["}
- stack, ok = [], True
- for c in s:
- if c in "([":
- stack.append(c)
- elif not stack:
- ok = False
- elif stack.pop() != op[c]:
- ok = False
- print(ok and not stack)
Variables
- case
- 0 (just changed)
Pick which string to check.
Quick check
Quick check: Is "([)]" balanced?
Where stacks show up#
- Undo in editors: each edit is a push, Ctrl+Z is a pop.
- Browser back: each page you open is pushed, Back pops it.
- The call stack: each function call pushes a frame (its own box of local variables), each return pops it.
Quick check
Quick check: On IRCTC you open Home, then Search Trains, then Seat Map. You press Back twice. Where are you?
Recursion that goes too deep fills the call stack. Python stops it with RecursionError (the default limit is about 1000 frames). Other languages call this a stack overflow.
The monotonic stack: next warmer day#
Daily Temperatures asks: for each day, how many days until a warmer one? Checking every later day for every day is O(n²). A stack does it in one pass. Keep the indexes of days still waiting for a warmer day. When a warmer day comes, it pops every colder day waiting on top and fills in their answers. Below, w is the waiting stack, enumerate gives each day's index i with its temperature x, and t[w[-1]] is the temperature of the day on top of w. Watch day 3 pop three days at once.
- t = [30, 28, 25, 31, 29]
- ans = [0] * len(t)
- w = []
- for i, x in enumerate(t):
- while w and t[w[-1]] < x:
- j = w.pop()
- ans[j] = i - j
- w.append(i)
- print(ans)
Variables
t
Five days of temperatures, in degrees.
The temperatures of waiting days never rise from bottom to top, which is why this is called a monotonic stack (monotonic means it only ever goes one way, here never up). Each index is pushed once and popped at most once, so the whole run is O(n).
Quick check
Quick check: Add a sixth day at 35 to the end of t. Which answers change?
The same stack in five languages#
Here is a stack class with push, pop, peek and is empty, written in five languages.
One last check#
Quick check
Quick check: You check "(()[" with the bracket stack. What happens?
Next, solve Valid Parentheses: it is the bracket check from this page with one more kind of bracket, {}.