Stacks, and the monotonic stack
- Use a Python list as a stack: push and pop at its end in O(1). Spot the problems that are a stack in disguise: brackets, undo, paths and nested strings
- Read a stack trace, say why deep recursion fails in Python, and rewrite a recursive walk with a stack you keep yourself
- Compare two samples of a call stack by the frames they share from the bottom, and list the end and start events in the order they happened
- Total each function's time from start and end events with a stack, with and without the functions it calls, and count a recursive function once
- Find the next larger value for every item in one pass with a monotonic stack, and say why it's O(n)
- Answer the follow-ups: what a sampler misses, why it can't count calls, millions of samples, a stack that knows its minimum, and trapped rain water
From stack samples to a trace
Anthropic software engineer candidates report a coding question about profiler samples (3 reports). A staff candidate was asked to find the slowest part of the code from samples like these (1 report). It starts like this:
A sampling profiler stops a program every so often and records its call stack. One sample is
(time, stack), wherestacklists function names, outermost call first, as a Python traceback does.Write
trace(samples). Return the events(time, kind, name), wherekindis"start"or"end", for every function call the samples show. A call that's gone in the next sample ended at that sample's time, and the last sample ends every call still open.
Sample Events (0, ["main"])(0, "start", "main")(10, ["main", "load"])(10, "start", "load")(20, ["main", "parse"])(20, "end", "load"),(20, "start", "parse")(30, [])(30, "end", "parse"),(30, "end", "main")
Then the interviewer asks for time: how long each function ran, and which one is slowest. After that come the cases real programs bring, such as a function that calls itself.
You don't write it yet. Working out which calls kept running between two samples is a stack question, so the first parts teach the stack itself, with the stack problems interviewers also ask, and part 4 turns to the samples. At the end you solve the whole problem, level by level, in an interview simulation with a 45-minute timer.
A stack is the order in which a program's calls open and close, and that order is exactly what profiler samples record. The idea of last in, first out comes back in the topological sort lesson, where depth-first search keeps the same kind of stack.
Last in, first out
Each stack in the samples is a Python list, with the outermost call first and the newest call at the end. A call is added at the end and removed from the end, so the list works as a stack:
stack = []
stack.append("main") # push
stack.append("load") # push
print(stack[-1]) # peek
print(stack.pop()) # pop
print(stack)
load
load
['main']
Here is the list after each step, drawn with its end on top:
A stack keeps things the way a pile of plates does. You add to the top and take from the top, so the last thing in is the first thing out. That rule is called LIFO, for last in, first out.
A stack has three operations:
- push puts an item on top:
append. - pop takes the top item off and returns it:
pop()with no index. - peek looks at the top without taking it:
stack[-1].
You don't need a special type for it in Python. A list already is a stack, as long as you only use its end.
In the editor, write replay(ops). Each op is a string, "push main", "pop" or "peek". Run them on one list, and return what each pop and peek gave back, in order.
Keep the top at the end of the list, because the front costs O(n) per push or pop
A list keeps its items side by side. Taking the last one moves nothing else. Taking the first one shifts every item behind it down one place:
pop() pop(0) Red leaves. pop() moves nothing else. pop(0) moves the 4 orange items behind it one place each.
Here are n pushes, then n pops, at each end:
def fill_end(n):
stack = []
for i in range(n):
stack.append(i)
def drain_end(n):
stack = list(range(n))
while stack:
stack.pop()
def fill_front(n):
stack = []
for i in range(n):
stack.insert(0, i)
def drain_front(n):
stack = list(range(n))
while stack:
stack.pop(0)
Timed:
n times each, in ms:
| n | At the end: push, pop | At the front: push, pop |
|---|---|---|
| 10,000 | 0.18, 0.25 | 7.29, 5.99 |
| 20,000 | 0.34, 0.48 | 30.70, 26.31 |
| 40,000 | 0.69, 0.97 | 136.68, 124.81 |
| 80,000 | 1.45, 2.09 | 560.13, 514.67 |
At the end the calls are append and pop(), and at the front insert(0, x) and pop(0).
Python 3.12, best of 5 runs with timeit, on the laptop these numbers come from.
Double n and the end's time doubles. That's O(1) per operation. For append it's amortized O(1), in the same sense as a dict's insert in the hash-maps lesson: now and then the list grows, and that rare cost spreads over all the appends.
Double n and the front's time grows about four times. That's O(n) per operation, and O(n²) for all of them. Either way the list takes O(n) memory for n items.
The table counts milliseconds. In the editor, write moves(n, front) to count the work behind them: how many times an item shifts one place when you pop all n items, from the front or from the end.
A stack fits whenever the last thing opened must close first
When does a problem call for a stack? Brackets are the clearest case.
Each closer pairs with the most recent opener that's still open. The ] closes the [, the } closes the {, and only then can the ) close the (.
Reach for a stack whenever the thing you deal with next is the most recent thing that isn't finished yet:
- An editor's undo pushes each edit and pops the latest one.
- In code, the bracket that must close next is the last one opened.
- In a running program, the function that returns next is the one called most recently. That's the call stack, the subject of part 2.
Undo, first on that list, is the plainest stack. In the editor, write typed(actions): each action is a word to type, or "undo", which takes back the latest word still there. Return the words left, joined by spaces.
Push each opener, and each closer must match the top
Counting brackets can't see their order
The obvious check counts each kind and compares the counts:
from collections import Counter
def balanced_by_count(text):
counts = Counter(text)
return all(counts[o] == counts[c] for o, c in ("()", "[]", "{}"))
for text in ["f(a[0], {k: v})", "([)]", "())(", "(("]:
print(f"{text:16} {balanced_by_count(text)}")
f(a[0], {k: v}) True
([)] True
())( True
(( False
Only the first one is balanced. Counts can't see order. In ([)] the ) arrives while [ is the bracket still waiting to close. In ())( the second ) arrives with nothing open.
A stack sees both problems. Push each opener. When a closer comes, the top of the stack must be its partner, and you pop it:
The stack ends empty, so every opener was closed.
Push each opener, and each closer must match the top. What happens on ([)]?
Recursion is a stack you don't see
Here's a small program that fails three calls deep:
import traceback
def parse(text):
print([frame.name for frame in traceback.extract_stack()])
return int(text)
def load(lines):
return [parse(line) for line in lines]
def main():
return load(["1", "2", "x"])
main()
['<module>', 'main', 'load', 'parse']
['<module>', 'main', 'load', 'parse']
['<module>', 'main', 'load', 'parse']
Traceback (most recent call last):
File "app.py", line 17, in <module>
main()
File "app.py", line 14, in main
return load(["1", "2", "x"])
^^^^^^^^^^^^^^^^^^^^^
File "app.py", line 10, in load
return [parse(line) for line in lines]
^^^^^^^^^^^
File "app.py", line 6, in parse
return int(text)
^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'x'
That's Python 3.12's output, with the folder cut from each path.
Every call pushes a frame, and a traceback prints the frames outermost first
main calls load, which calls parse once per line. Not counting <module>, at most how many frames are on the call stack?
Each recursive call adds a frame, and Python's default limit is 1,000
A function that calls itself pushes one more frame per call. Sum a nested list that way:
def total(nested):
s = 0
for item in nested:
if isinstance(item, list):
s += total(item)
else:
s += item
return s
# [1, [1, [1, ...]]], depth lists deep
def nest(depth):
nested = [1]
for _ in range(depth - 1):
nested = [1, nested]
return nested
print(nest(3))
print(total(nest(3)))
[1, [1, [1]]]
3
Follow one run. traced is total with two prints: a line when a call starts and a line when it returns, indented one step for each level d:
def traced(nested, d=0):
pad = " " * d
print(f"{pad}call on {nested}")
s = 0
for item in nested:
if isinstance(item, list):
s += traced(item, d + 1)
else:
s += item
print(f"{pad}return {s}")
return s
traced([1, [2, [3]]])
call on [1, [2, [3]]]
call on [2, [3]]
call on [3]
return 3
return 5
return 6
On the way down, each call adds the numbers it holds until it meets an inner list, then calls total on that list and waits. The outer call has s = 1 when it calls total([2, [3]]). That call has s = 2 when it calls total([3]). Each waiting call keeps its own s in its own frame.
On the way back up, total([3]) returns 3. The middle call adds it to its 2 and returns 5. The outer call adds the 5 to its 1 and returns 6.
One frame for each level of nesting. The stack is deepest at the innermost list.
Python caps how many frames there can be. sys.getrecursionlimit() returns that cap, which its docs call the maximum depth of the Python interpreter stack. It's 1,000 by default.
Called from a script's top level, total(nest(999)) returned 999, and total(nest(1000)) raised RecursionError: maximum recursion depth exceeded. Here are the two stacks at their deepest:
total(nest(999)) | total(nest(1000)) | |
|---|---|---|
| frame 1 | <module> | <module> |
| frames 2 and up | total, calls 1 to 999 | total, calls 1 to 1,000 |
| in all | 1,000 frames: it fits | 1,001 frames: RecursionError |
The script's own module frame was already on the stack. So 999 calls of total filled all 1,000 frames, and the 1,000th call was one too many.
At depth 5,000 the traceback was only 14 lines long. Python folds the repeats into one line: [Previous line repeated 996 more times].
In the editor, write depth(nested) with recursion, the way total walks: how many lists deep a nested list goes. Then write fits(levels): whether a recursive walk that many levels deep, called from a script's top level, stays within 1,000 frames. nest is the helper from above.
A list of the lists still to read replaces the recursion
Ask what each recursive call remembers. Here it's only the list it still has to read. So keep a list of the lists waiting to be read:
def total(nested):
s, stack = 0, [nested]
while stack:
for item in stack.pop():
if isinstance(item, list):
# where the recursion called total(item)
stack.append(item)
else:
s += item
return s
print(total([1, [2, 3], [4, [5]]]))
print(total(nest(100_000)))
15
100000
The stack version pops a list, adds its numbers and pushes its sublists. In what order does it add the items of [1, [2, 3], [4, [5]]]?
The stack changed the order, and a flatten must keep it
The stack version of total added the items of [1, [2, 3], [4, [5]]] in the order 1, 4, 5, 2, 3. The recursion reads them 1, 2, 3, 4, 5. The stack version finishes the list in hand before it opens the lists it found inside, and the list it pushed last comes off first. A sum doesn't care. A flatten does.
Flatten Nested List Iterator is on the compiled LeetCode list for OpenAI (1 source). An iterator hands out one item per call. A recursive generator can do that too, but it hits the same recursion limit. Flattening everything up front does all the work before the first item is asked for. So the iterator keeps a stack itself, and it must hand the items out in reading order.
In the editor, write flatten(nested) with a stack you keep yourself, no recursion. It returns the items in reading order, 1, 2, 3, 4, 5, not the order the stack version of total added them.
Write flatten(nested): every item of a nested list that isn't itself a list, in the order you'd read them from left to right. [1, [2, [3, 4], 5], [], 6] gives [1, 2, 3, 4, 5, 6]. Use your own stack, not recursion: one test nests 5,000 lists deep.
Input that opens and closes
The same idea parses text with levels in it. Whenever part of the input opens something that a later part closes, the open things wait on a stack. A .. in a path cancels the directory entered last. A ] closes the last [. In part 5, a profiler's end event closes the start it matches.
.. pops the directory entered last
Simplify Path is on the compiled LeetCode list for OpenAI (1 source). Turn a Unix path into its shortest form, where . means this directory and .. means the parent.
Split the path on /, and walk the parts with a stack of directory names. Skip an empty part and .. Pop for .., unless the stack is already empty. Push any other name. At the end, join the stack with / behind a leading /.
What's the shortest form of /srv//app/./logs/../cache/?
At [, push what you've built so far. At ], pop it and repeat
In the format 3[ab]c, a number before brackets repeats what's inside, and brackets can nest:
def decode(text):
stack, current, count = [], "", 0
for ch in text:
if ch.isdigit():
count = count * 10 + int(ch)
elif ch == "[":
stack.append((current, count))
current, count = "", 0
elif ch == "]":
before, times = stack.pop()
current = before + current * times
else:
current += ch
return current
print(decode("3[ab]c"))
print(decode("2[a3[b]]"))
print(decode("x10[y]z"))
What does decode("2[a3[b]]") give?
A length in front of each string needs no stack
A related problem has no stack at all. Encode and Decode Strings is on the compiled LeetCode list for OpenAI (1 source). A prep guide lists it for Anthropic (1 source). Pack a list of strings into one string, and get the same list back.
A separator breaks as soon as a string contains it. Put each string's length in front instead, and the decoder never has to guess:
def encode(strings):
return "".join(f"{len(s)}:{s}" for s in strings)
packed = encode(["a:b", "", "3:x", "naïve"])
print(packed)
encode puts each string's length and a colon in front of it. What does encode(["a:b", "", "3:x", "naïve"]) give?
What changed between two samples
Back to the profiler. A sample is a pair (time, stack). The stack lists the calls outermost first, the way extract_stack printed them. Here are two samples in a row:
(30, ["main", "load", "parse"])
(40, ["main", "save"])
What happened in between?
Frames shared from the bottom kept running, and the rest ended or started
Compare the stacks from the bottom, depth by depth:
main is shared: the same call. load and parse ended, in red, and save started, in green.
The frames the two stacks share from the bottom are calls that kept running. From the first difference up, every frame of the old stack is a call that ended. Every frame of the new one is a call that started.
The order is forced too. parse had to return before load could. load had to return before main could call save. So the stack went through these steps between the two samples:
The ends go innermost first, and the starts go outermost first:
[(40, 'end', 'parse'), (40, 'end', 'load'), (40, 'start', 'save')]
Comparing two stacks costs O(d) for depth d. So turning s samples into events costs O(s·d), and you only ever hold the previous stack.
In the editor, write shared(before, after): how many frames two stacks share from the bottom. The demo line compares the samples at 30 and 40, which share only main.
In this lesson, a call ends at the first sample that doesn't show it
Why the time 40? Look at when parse was seen:
parse is in the samples at 20 and 30, and not at 10 or 40.
The sampler saw parse at 30 and not at 40. So it ended somewhere in between, and nothing in the samples says where. The same goes for its start, somewhere after 10 and by 20.
This lesson and its practice problem use one rule: a call starts at the first sample that shows it, and ends at the first sample that doesn't. Each sample then stands for the time until the next one.
Every start after the first sample, and every end before the last, is off by less than one sampling interval. Calls already running at the first sample, or still running at the last, are cut off at that sample's time. Nothing says how long they ran outside the samples.
SAMPLES in the editor is eight samples of a short run, one every 10 ms, with the samples at 30 and 40 among them. Write call_window(samples, name): the start and end that this rule gives a call of name.
A frame is the same call only if every frame below it matches
Take ["main", "a", "b"] followed by ["main", "b"]:
a is gone, so this b is a new call, made by main.
The first b was called by a. The second was called by main, so it's a different call that happens to run the same function. Comparing names without their position gets this wrong:
def by_set(before, after, time):
gone = [n for n in reversed(before) if n not in set(after)]
new = [n for n in after if n not in set(before)]
return [(time, "end", n) for n in gone] + [(time, "start", n) for n in new]
print(by_set(["main", "a", "b"], ["main", "b"], 1))
print(by_set(["main", "f"], ["main", "f", "f"], 3))
[(1, 'end', 'a')]
[]
The first answer should be [(1, 'end', 'b'), (1, 'end', 'a'), (1, 'start', 'b')]. Recursion breaks it worse: from ["main", "f"] to ["main", "f", "f"] a second call of f started, and by_set reports nothing. Count the shared frames by position and both come out right.
In the editor, finish events_between(before, after, time): count the shared frames, then build the ends and the starts. It's the heart of level 1 of the practice problem. There you run it over each pair of neighboring samples, starting from an empty stack, and end each open call after the last sample. That whole loop is called trace(samples).
Finish events_between(before, after, time). before and after are two samples of a call stack, outermost call first, and a frame is the same call in both only when it and every frame below it match. Return the (time, "end", name) events for the calls in before that aren't still running, innermost first, then the (time, "start", name) events for the new calls in after, outermost first.
Start and end events nest like brackets
Eight samples give eight events
Here are eight samples of a short run, taken every 10 ms. Below them are the events that events_between gives on each neighboring pair, with what's still open closed at the last sample:
SAMPLES = [
(0, ["main"]),
(10, ["main", "load"]),
(20, ["main", "load", "parse"]),
(30, ["main", "load", "parse"]),
(40, ["main", "save"]),
(50, ["main", "save"]),
(60, ["main", "save"]),
(70, ["main"]),
]
EVENTS = [
(0, "start", "main"),
(10, "start", "load"),
(20, "start", "parse"),
(40, "end", "parse"),
(40, "end", "load"),
(40, "start", "save"),
(70, "end", "save"),
(70, "end", "main"),
]
print(len(SAMPLES), "samples,", len(EVENTS), "events")
8 samples, 8 events
Write each start as ( and each end as ), and the eight events read ((())()): balanced brackets. Every start has an end, and a call can't end while a call it made is still open. Drawn over time, each call is a bar that sits inside its caller's bar:
That nesting makes timing them a stack problem.
In the editor, write as_brackets(events), which turns a list of events into its bracket string. Then write nests(events), which checks with a stack that each end closes the innermost open call and nothing is left open.
Self time counts the samples with a function on top, total time the samples with it anywhere
A profiler reports two times for each function, and both come from counting the samples.
Samples come every 10 ms, and each stands for the 10 ms after it. main is in all 7 that count, but on top in only one. What are its self and total time?
From the events, a call's total time runs from its start to its end
Push the start time with the name, and the end event pops it:
def call_durations(events):
stack, total = [], {}
for time, kind, name in events:
if kind == "start":
stack.append((name, time))
else:
name, start = stack.pop()
total[name] = total.get(name, 0) + time - start
return total
print(call_durations(EVENTS))
{'parse': 20, 'load': 30, 'save': 30, 'main': 70}
Which function is slowest? By total time it's always the outermost one, here main at 70, because its time contains everyone else's. Self time points at the code that's actually busy: save, at 30.
Adding up a recursive function's calls counts a moment more than once
A recursive function is open more than once at the same moment. Here f calls itself twice:
REC = [
(0, "start", "main"),
(0, "start", "f"),
(10, "start", "f"),
(20, "start", "f"),
(30, "end", "f"),
(30, "end", "f"),
(40, "end", "f"),
(40, "end", "main"),
]
print(call_durations(REC))
{'f': 70, 'main': 40}
That's 70 for f in a program that ran for 40. Here are the calls as bars, with how many calls of f are open in each stretch:
Calls of f open: 1 from 0 to 10, 2 from 10 to 20, 3 from 20 to 30, then 1 to 40.
Adding the calls gives 40 + 20 + 10 = 70. The stretch from 10 to 20 was counted twice, and the one from 20 to 30 three times. A function's total time should be how long at least one of its calls was open: 40.
In the editor, write most_open(events): for each function, the most of its calls open at the same moment. REC is the recursive run above.
Count only the outermost open call of each function, as cProfile's cumtime does
cProfile gives a recursive function the time at least one of its calls was open, not the sum of its calls. Here's a function that keeps the CPU busy for 10 ms and then calls itself, three calls deep:
import cProfile
import time
def spin(seconds):
end = time.perf_counter() + seconds
while time.perf_counter() < end:
pass
def walk(depth):
spin(0.01)
if depth > 1:
walk(depth - 1)
cProfile.run("walk(3)", sort="cumulative")
In its row for walk, cProfile printed 3/1 in the ncalls column and a cumtime of 0.030 s. That's the length of the outermost call alone. Adding up the three calls would give about 0.060.
The docs explain both. Two numbers in that column, like 3/1, mean the function recursed. And cumtime stays accurate even for recursive functions.
The fix is to count a call's time only when it's the outermost open call of its function. A Counter of open calls per name tells you that in O(1). It's the counting tool from the hash-maps lesson. Here it is on REC, the run where f calls itself twice:
| Event | Time | Calls of f open | Adds |
|---|---|---|---|
| start f | 0 | 1 | |
| start f | 10 | 2 | |
| start f | 20 | 3 | |
| end f | 30 | 2 | |
| end f | 30 | 1 | |
| end f | 40 | 0 | 40 - 0 |
When an end brings a name's count down to 0, that call was the outermost one, and only its length is added.
Self time needs no fix, since only one call is innermost at a time:
print(self_times(REC))
{'main': 0, 'f': 40}
Both passes are O(n) time for n events, and O(d + k) memory for stack depth d and k different functions.
In the editor, finish total_times(events) with that fix. stack holds each open call with its start time, and open_calls counts the open calls of each name.
Finish total_times(events): for each function, how long at least one of its calls was open, with the functions it calls included. events are (time, kind, name) tuples that nest like brackets. A function open at two depths counts each moment once. Every function in events is a key, even when its time is 0.
A stack that stays in order: the monotonic stack
A new problem, and one more way to use a stack. For every value in a list, find the next value to its right that's larger, or None if there isn't one.
The obvious way scans ahead from each item until it finds something larger:
def next_larger_scan(values):
answer = []
for i, v in enumerate(values):
found = None
for w in values[i + 1:]:
if w > v:
found = w
break
answer.append(found)
return answer
print(next_larger_scan([5, 3, 1, 4, 2, 6]))
For each of 5, 3, 1, 4, 2, 6, the next value to its right that's larger. What's the list?
Each index is pushed once and popped at most once, so the pass is O(n)
The while inside the for can pop several items at once: the 6 popped three. But every index is pushed once and popped at most once. So across the whole run, the pops add up to at most n. Here it was 6 pushes and 5 pops.
That's O(n) time, and O(n) memory for the stack and the answer. Measured on lists that only go down, best of 3 runs or more:
| n | next_larger_scan | The waiting stack |
|---|---|---|
| 1,000 | 5.2 ms | 0.046 ms |
| 2,000 | 21.4 ms | 0.090 ms |
| 4,000 | 86.8 ms | 0.182 ms |
| 8,000 | 355.3 ms | 0.374 ms |
The scan grows four times when n doubles, and the stack two times. At 8,000 items the stack is about 950 times faster.
In the editor, finish next_larger_counted(values): the next larger value for each item, found with the waiting stack, plus a count of every comparison the while makes. The count stays under 2n.
After the pops, the top is the nearest earlier value the new one didn't beat
The same stack answers the mirror question too. Take the 4 in [5, 3, 1, 4, 2, 6]. It pops 1 and 3, and the 5 is left under it. Every value between the 5 and the 4 was beaten and popped, so the 5 is the nearest earlier value the 4 didn't beat.
So next larger reads its answers off the items it pops. Previous larger reads its answer off the item that survives.
The same shape answers how many days until a warmer day, how far back a price's run goes, and how much rain water bars can hold. The rain water comes up in the follow-ups.
In the editor, write spans(prices) with the value that survives on top. For each day, it gives how many days in a row, ending that day, had a price at most that day's price.
Write spans(prices): for each day, how many days in a row, ending with that day, had a price at most that day's price. [7, 3, 4, 4, 2, 8, 5] gives [1, 1, 2, 3, 1, 6, 1]. Make it one pass with a stack of indices: one test counts the comparisons and fails past 4 per day.
Daily temperatures with a monotonic stack, the same next-larger idea with distances instead of values. The drawing starts here and the code at 9:25.
A worked example: rocks that collide
The prompt, in the shape of Asteroid Collision, which is on the compiled LeetCode list for OpenAI (1 source): a row of rocks drifts along a line, all at the same speed. Each rock is a nonzero integer. Its size is the absolute value, and its sign is its direction: positive to the right, negative to the left. When two rocks meet, the smaller one breaks up, and if they're the same size both do. Return the rocks left once nothing else can meet, in order. Here, [4, 7, -3, 2, -9, 6, -6, -1, 5].
Only a right-mover with a left-mover somewhere to its right can collide
Rocks 4, 7, -3, 2, -9, 6, -6, -1, 5: positive moves right, negative left. When two meet, the smaller breaks, and equal ones both break. Which survive?
Simulating one collision per scan is O(n²)
The obvious answer: find the first right-mover directly followed by a left-mover, settle that collision, and start the scan over:
def collide_rounds(rocks):
rocks = list(rocks)
while True:
for i in range(len(rocks) - 1):
if rocks[i] > 0 and rocks[i + 1] < 0:
a, b = rocks[i], -rocks[i + 1]
if a > b:
del rocks[i + 1]
elif a < b:
del rocks[i]
else:
del rocks[i:i + 2]
break
else:
return rocks
rocks = [4, 7, -3, 2, -9, 6, -6, -1, 5]
print(collide_rounds(rocks))
[-9, -1, 5]
Each round scans up to n rocks and removes one or two, so it's O(n²). Say that, and move on.
Keep the survivors on a stack, and let each left-mover fight the top
Read the rocks left to right, and keep the survivors so far on a stack. The survivors never threaten each other, so the stack is settled.
- A right-mover goes on top. Nothing to its left can reach it, and whatever might hit it hasn't arrived yet.
- A left-mover meets the right-movers on the stack nearest first, which is the top. It breaks every smaller one it reaches, stops at a bigger one, and breaks up along with an equal one. If it gets past every right-mover, it joins the stack for good.
Trace it the way you'd narrate it at the whiteboard:
| Rock | What happens | Survivors, top on the right |
|---|---|---|
| 4 | push | 4 |
| 7 | push | 4, 7 |
| -3 | breaks on 7 | 4, 7 |
| 2 | push | 4, 7, 2 |
| -9 | 2, then 7, then 4 break | -9 |
| 6 | push | -9, 6 |
| -6 | 6 and -6 both break | -9 |
| -1 | nothing moving right to hit | -9, -1 |
| 5 | push | -9, -1, 5 |
The -9 shows the stack at work. It pops the 2, the 7 and the 4, nearest first, and then it's the bottom of the stack. The survivors, [-9, -1, 5], are the same as collide_rounds gives.
In the editor is collide, the stack version, with one change to its while condition. It gives the wrong survivors for the worked example's row. Use the trace table to find the bug, and fix it.
Test the edges you named, then give the cost
Here's the fixed collide. The while runs only while the new rock moves left and the top of the stack moves right:
def collide(rocks):
survivors = []
for rock in rocks:
alive = True
while alive and rock < 0 and survivors and survivors[-1] > 0:
top = survivors[-1]
if top <= -rock:
# the rock on the stack breaks
survivors.pop()
if top >= -rock:
# the new rock breaks
alive = False
if alive:
survivors.append(rock)
return survivors
print(collide(rocks))
[-9, -1, 5]
Before you say you're done, run collide on the edge cases you named at the start.
for row in [[], [3, -3], [-2, -1, 1, 2], [1, -2, 3], [5, 5, -5]]:
print(f"{str(row):16} {collide(row)}")
[] []
[3, -3] []
[-2, -1, 1, 2] [-2, -1, 1, 2]
[1, -2, 3] [-2, 3]
[5, 5, -5] [5]
[3, -3] breaks both. [-2, -1, 1, 2] comes back unchanged, since nothing meets. In [5, 5, -5], the -5 breaks along with the nearer 5 and never reaches the other one. The two versions also agreed on 2,000 random rows of up to 12 rocks.
Each rock is pushed at most once and popped at most once, the same argument as the monotonic stack: O(n) time and O(n) memory. Measured on n - 1 rocks of size 1 moving right, then one of size n moving left, where the simulation finds one collision per scan, best of 3 runs or more:
| n | collide_rounds | collide |
|---|---|---|
| 1,000 | 15.1 ms | 0.103 ms |
| 2,000 | 67.6 ms | 0.208 ms |
| 4,000 | 274.4 ms | 0.410 ms |
| 8,000 | 1,136.5 ms | 0.837 ms |
The two versions were checked with a random test. In the editor, write first_disagreement(fast, slow, seed): it gets two functions, tries 2,000 random rows, and returns the first row where they differ. The demo line passes sorted and list, which disagree on most rows, so you see a failure come back.
What interviewers ask next
The practice problem's README lists the first ones: what a sampler misses, why it can't count calls, millions of samples, and several threads. The rest come up around the other stack questions.
What can a sampler miss? Any call that starts and ends between two samples
The samples see f, f, f and then main. Every call of f that starts and ends between two samples is never seen.
Here f ran 8 times in 30 ms, and a sample came every 10 ms. Three samples landed inside a call of f, and the other 5 calls fell between samples.
With names alone, f at 0, 10 and 20 looks like one long call from 0 to 30. If each frame carries a call id, it's 3 calls. Either way, 5 of the 8 never show up.
Python 3.15's sampling profiler documents this trade: very short calls may be missed if they finish between samples. It estimates time from counts instead. It counts how often each function appears in the samples and multiplies by the sampling interval. So the time comes out close, and the call count doesn't.
A bigger made-up run shows it. main calls f 996 times, each call 1 to 5 ms long, with 0.5 to 1.5 ms of main's own work between, sampled every 10 ms. The times are in microseconds. tagged holds the samples with a call id on each frame, a pair (name, id), and plain holds the same samples with names only:
import random
rng = random.Random(1)
calls, t = [], 0
while True:
length, gap = rng.randint(1_000, 5_000), rng.randint(500, 1_500)
if t + length + gap > 4_000_000:
break
calls.append((t, t + length))
t += length + gap
end = t
def frames_at(time):
for k, (start, stop) in enumerate(calls):
if start <= time < stop:
return [("main", -1), ("f", k)]
return [("main", -1)]
tagged = [(time, frames_at(time)) for time in range(0, end, 10_000)] + [(end, [])]
plain = [(time, [name for name, _ in stack]) for time, stack in tagged]
The table runs three functions you write in the practice problem:
trace(samples), level 1, turns samples into start and end events:events_betweenon each neighboring pair.trace_calls(samples), level 3, does the same for(name, id)frames, which match only when both parts do.function_times(events, include_callees=True), level 2, gives each function's total time.
| truth | from names, trace | with call ids, trace_calls | |
|---|---|---|---|
calls of f | 996 | 73 starts | 304 starts |
total time in f | 2,982.1 ms | 3,037.3 ms | 3,037.3 ms |
The 401 samples put f's time within 2 percent. With names alone, f returning and being called again between two samples looks like one long call, so 996 calls became 73. Call ids separate those, and trace_calls found 304. Still, 692 of the 996 calls never appeared in any sample. The docs say it plainly: when you need exact call counts, sampling can't give them.
TIMELINE in the editor is the 30 ms from the figure above, as a string: F is a millisecond with f running, and . one without. Write runs(timeline) to turn it into calls, then seen(calls, every) to count the calls a sampler sees.
Why sample at all? cProfile, which records every call, made fib(22) take 4 times as long
Recording every call and return is what cProfile does, and it slows the program down:
import cProfile
import timeit
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
profiler = cProfile.Profile()
def profiled():
profiler.enable()
fib(22)
profiler.disable()
plain = min(timeit.repeat(lambda: fib(22), number=1, repeat=5))
traced = min(timeit.repeat(profiled, number=1, repeat=5))
fib(22) makes 57,313 calls. It took 1.58 ms on its own, and 6.27 ms with cProfile on: 4.0 times as long.
The profile docs set the two side by side. A statistical profiler samples where the program is at random moments and deduces where time is being spent. It reads the stack from outside, so the program runs at full speed. The price is the sampler's blind spot: calls that start and end between two samples.
So use a tracer when you need exact counts and can afford the slowdown. Use a sampler on a production server.
In the editor, write fib_calls(n): how many calls fib(n) makes, built up in a loop. For 22 it's 57,313. Then write cost_per_call_ns(plain_ms, traced_ms, calls): what the tracer added to each call, in nanoseconds.
What about millions of samples? Hold only the previous stack
trace(samples), level 1 of the practice problem, turns all the samples into events: events_between on each neighboring pair, from an empty stack, with the last sample ending what's still open. It only needs the previous stack. So write it as a generator that yields each sample's events as it goes. It then holds two stacks at a time, O(d) memory for depth d, however many samples stream through. function_times(events, include_callees), level 2, turns the events into each function's time. It holds the open calls and one total per function, so it can read the events as they stream in too.
To see where the time goes, count identical stacks:
from collections import Counter
collapsed = Counter(";".join(stack) for _, stack in SAMPLES)
for stack, count in collapsed.items():
print(stack, count)
main 2
main;load 1
main;load;parse 2
main;save 3
That's each distinct stack and how many samples showed it. It's the collapsed format that flame graph tools read. The docs describe it: one line per stack, function names joined by semicolons from the bottom of the stack to the top, then a space and the sample count.
events_between, the function you wrote in part 4, is at the top of the editor. Finish the generator stream(samples): it yields each sample's events and keeps only the previous stack and time.
What about several threads? Keep one previous stack per thread
Each sample then carries a thread id, and each thread has its own stack. Keep the previous stack per thread in a dict keyed by thread id. Compare each sample only with that thread's last one.
Tag each event with its thread too, and keep one stack per thread in function_times, the practice problem's function that turns events into time. Merged into one list, two threads' events don't nest like brackets.
a runs on thread 1 from 0 to 2, and b on thread 2 from 1 to 3. Merged, the events are start a, start b, end a, end b. Do they nest like brackets?
A stack that always knows its minimum stores the smallest so far with each item
Push, pop and min(), all O(1). Store each item with the smallest value at or below it, so the minimum is always on top:
class MinStack:
def __init__(self):
# (value, smallest so far)
self.items = []
def push(self, x):
low = min(x, self.items[-1][1]) if self.items else x
self.items.append((x, low))
def pop(self):
return self.items.pop()[0]
def min(self):
return self.items[-1][1]
s = MinStack()
for x in [5, 3, 7, 3, 1]:
s.push(x)
print("push", x, "min", s.min())
for _ in range(4):
print("pop", s.pop(), "min", s.min())
Push 5, 3, 7, 3 and 1, then pop once. What does min() return?
Trapped rain water fills in layers with a decreasing stack
Trapping Rain Water is on the compiled LeetCode lists for OpenAI and Airbnb (2 sources). The lesson on two pointers and the sliding window solves it with a pointer at each end. A decreasing stack of bar indices solves it too.
When a taller bar arrives, pop the bar it beats. That bar is the floor of a pool, the new bar is its right wall, and the bar now on top is its left wall. Fill the pool up to the lower wall:
def trapped(heights):
water, stack = 0, []
for i, h in enumerate(heights):
while stack and heights[stack[-1]] < h:
floor = heights[stack.pop()]
if not stack:
break
left = stack[-1]
water += (min(heights[left], h) - floor) * (i - left - 1)
stack.append(i)
return water
print(trapped([3, 0, 1, 0, 2, 0, 4]))
Bars 3, 0, 1, 0, 2, 0, 4. How much water do they hold?
How would you test it? Check a rule that holds for every input
Beyond the examples, test a property that has to hold for every input. In each stretch between two samples, either the stack is empty or exactly one call is innermost. So the self times must add up to the time the stack wasn't empty.
The test below checks that on 3,000 random runs, against the practice problem's two functions. trace(samples) turns the samples into start and end events, and function_times(events, include_callees=False) gives each function's self time from them. busy_time(samples) is the time the stack wasn't empty, and you write it in the editor:
import random
def test_self_times_add_up_to_busy_time():
rng = random.Random(3)
for _ in range(3000):
t, samples = 0, []
for _ in range(rng.randint(0, 8)):
t += rng.randint(1, 5)
samples.append((t, [rng.choice("abc") for _ in range(rng.randint(0, 4))]))
own = function_times(trace(samples), include_callees=False)
assert sum(own.values()) == busy_time(samples)
Random stacks over three names hit recursion, new callers and empty stacks far more often than hand-written cases do.
In the editor, write busy_time(samples): add up each gap between neighboring samples where the first sample's stack isn't empty. With it, the test passes on all 3,000 runs.
The practice problem, start to finish
That's every piece the practice problem needs. It asks for every level from the start of the lesson, from a blank file, and the interviewer follows up after each one.
1.You push 1, 2 and 3 onto a stack, then pop twice. What comes out, and what does each operation cost on a Python list used with
appendandpop()?2.One sample shows
["main", "load", "parse"]at time 30 and the next shows["main", "save"]at time 40. What events come at time 40, in order?3.Two samples in a row show
["main", "a", "b"]and then["main", "b"]. What happened between them?4.
fcalls itself: the outer call runs from 0 to 40 and the inner one from 10 to 30, and nothing else runs inside them. What isf's total time, callees included?5.The monotonic stack's next-larger loop has a
whileinside afor. Why is it O(n) and not O(n²)?6.A loop calls a 2 ms function a thousand times, and a sampler takes a sample every 10 ms. Which result can you trust?
Practice
Sources (15)
- Data Structures: Using Lists as Stacks · Python 3.12 documentation · Oct 26, 2026
“To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index.”
- Data Structures: Using Lists as Queues · Python 3.12 documentation · Oct 26, 2026
“While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).”
- traceback: extract_stack · Python 3.12 documentation · Oct 26, 2026
“Extract the raw traceback from the current stack frame.”
- sys: getrecursionlimit · Python 3.12 documentation · Oct 26, 2026
“Return the current value of the recursion limit, the maximum depth of the Python interpreter stack.”
- sys: setrecursionlimit · Python 3.12 documentation · Oct 26, 2026
“This should be done with care, because a too-high limit can lead to a crash.”
- The Python Profilers: Instant User's Manual · Python 3.12 documentation · Oct 26, 2026
“for the total time spent in the given function (and excluding time made in calls to sub-functions)”
- The Python Profilers: Instant User's Manual, cumtime · Python 3.12 documentation · Oct 26, 2026
“is the cumulative time spent in this and all subfunctions (from invocation till exit). This figure is accurate even for recursive functions.”
- The Python Profilers: Instant User's Manual, ncalls · Python 3.12 documentation · Oct 26, 2026
“When there are two numbers in the first column (for example 3/1), it means that the function recursed.”
- The Python Profilers: What Is Deterministic Profiling? · Python 3.12 documentation · Oct 26, 2026
“statistical profiling (which is not done by this module) randomly samples the effective instruction pointer, and deduces where time is being spent.”
- profiling.sampling: What is statistical profiling? · Python 3.15 documentation · Nov 10, 2026
“Statistical profiling builds a picture of program behavior by periodically capturing snapshots of the call stack.”
- profiling.sampling: When to use a different approach, short-lived functions · Python 3.15 documentation · Nov 10, 2026
“The trade-off is that very short-lived functions may be missed if they happen to complete between samples.”
- profiling.sampling: How time is estimated · Python 3.15 documentation · Nov 10, 2026
“Tachyon counts how many times each function appears in the collected samples, then multiplies by the sampling interval to estimate time.”
- profiling.sampling: When to use a different approach · Python 3.15 documentation · Nov 10, 2026
“When you need exact call counts, sampling cannot provide them.”
- profiling.sampling: Collapsed stacks format · Python 3.15 documentation · Nov 10, 2026
“Each line contains semicolon-separated function names representing the call stack from bottom to top, followed by a space and the sample count.”
- profiling.sampling: Profiling modes · Python 3.15 documentation · Nov 10, 2026
“Wall-clock mode (--mode=wall) captures all samples regardless of what the thread is doing. This is the default mode ... In wall-clock mode, samples are recorded whether the thread is actively executing Python code, waiting for I/O, blocked on a lock, or sleeping. ... CPU mode (--mode=cpu) records samples only when the thread is actually executing on a CPU core”