Trace recursive calls as frames on a stack.
Use it when a question about an input can be answered from the same question about a smaller input. Signal words: the same question on a smaller input, a function that calls itself, a base case.
Base case the smallest input, answered at once. Write it first.
Recursive case call the same function on a smaller input, and trust that it returns the right answer. Combine that answer with this call's own part.
Progress every call must move toward the base case.
Cost one frame for each open call. The time is the number of calls, and the extra space is the recursion depth.
In this lesson you learn what happens inside the computer when a function calls itself. You see the frames pile up and the values come back down, and you learn where the limit on the depth comes from. You also learn when to replace a recursion with a loop.
You work on the reply threads of a social app. Many conversations are chains: a comment, one reply to it, one reply to that reply, and so on.
A list replies says which comment answers each comment, or -1 when nobody does.
Your team lead says: The thread header must show how many comments are in the chain that starts at a given comment.
Here is a short test: five comments, numbered 0 to 4, with replies = [2, 4, 1, -1, -1]. Comment 0 is answered by comment 2, comment 2 by comment 1, and comment 1 by comment 4. Comment 4 has no reply, so the chain from comment 0 is 0, 2, 1, 4: four comments.
So the task is this: count the comments in the chain from a start comment.
You read a repair manual. Step 4 says: "First do the checklist on page 90." You put a bookmark at step 4 and turn to page 90.
Page 90 says: "First do the test on page 120." You put a second bookmark and turn to page 120. That page has no further instruction, so you finish it.
Then you go back to the last bookmark, finish page 90, and go back to the first bookmark. The bookmarks are stack frames: each one marks a task that is waiting. The newest bookmark is removed first.
A repair manual: each bookmark marks a task that is waiting, and the newest bookmark is removed first.
Before you write code, solve the test by hand. Notice what you must remember while you work.
Solve it by hand: Five comments: how long is the chain from comment 0?. The hand-solve sheet loads in your browser.
You write the question as a function. To count the chain from a comment, you ask the same question about its reply, and then add one for the comment itself. You keep a list of the questions that are still waiting.
The replies are [2, 4, 1, -1, -1]. Each row is one step. The waiting questions are listed from the oldest to the newest.
| Step | What you do | Waiting questions |
|---|---|---|
| 1 | Ask about comment 0. It has a reply, 2. | 0 |
| 2 | Ask about comment 2. It has a reply, 1. | 0, 2 |
| 3 | Ask about comment 1. It has a reply, 4. | 0, 2, 1 |
| 4 | Ask about comment 4. It has no reply, so the answer is 1. | 0, 2, 1, 4 |
| 5 | Comment 1 gets 1 and adds itself: 2. | 0, 2, 1 |
| 6 | Comment 2 gets 2 and adds itself: 3. | 0, 2 |
| 7 | Comment 0 gets 3 and adds itself: 4. | 0 |
At the deepest point four questions were waiting at once. A chain of n comments keeps n questions waiting.
Start with a correct version. It reads like the question itself.
def chain_length(replies, start):
if replies[start] == -1: # no reply: the chain ends here
return 1
below = chain_length(replies, replies[start]) # the same question, one comment further
return 1 + belowThis is correct. It costs one call for each comment: O(n) time. The team keeps it as the reference.
Now check the real size.
Some threads are chains of 20,000 comments.
Run the function on a chain of comments in Python and look at what happens:
RecursionError: maximum recursion depth exceeded.The function is not slow. It stops, because every waiting question needs a frame, and there is a limit on the frames.
Predict the limit
Q A thread is a chain of 20,000 comments. You call the first attempt in Python with the default settings. What happens?
Answer: C
The function needs one open frame for each comment, and Python allows about 1,000. The error comes at once, not after a long run, and it gives no partial answer.
The first attempt is correct on small threads. Now the team needs to know why it stops, and what to do about it.
First look at what a call is. When a function calls another one, the computer needs a place to keep the caller's variables and the place to return to. That place is a frame, and the frames sit on the call stack.
Follow the chain from comment 0. Each call to chain_length pushes a new frame on top. The calls above wait for nothing, and the calls below wait for the one above.
Each call pushes a frame. The calls below wait, and the newest call is on top.
The base case is the first call that does not call again. Comment 4 has no reply, so its call returns 1 at once. Its frame is removed.
Now the value travels back. Comment 1 was waiting for that 1. It adds itself and returns 2, and its frame is removed. The values come back in the reverse order of the calls, so the newest call finishes first.
The base case returns first, and each frame adds itself and returns to the frame below.
Exercise · Predict the output: In what order do the answers come back?. The function prints `start:result` as each call is about to return. What does the call on comment 0 print?
replies = [2, 4, 1, -1, -1]
def chain_length(start):
if replies[start] == -1:
result = 1
else:
result = 1 + chain_length(replies[start])
print(f"{start}:{result}")
return result
chain_length(0)The count is built on the way back. This tells us how to do better when the chain is long. The loop can add one on the way forward, and it needs no frames at all.
Race: A chain measured by recursion, against a loop. The operation counter loads in your browser.
The race measures the frames open at once, by running the instrumented function. For a chain of 1,000 comments the recursion keeps 1,000 frames open, and for 10,000 comments it keeps 10,000. The loop keeps one in every case.
The chain has six comments, replies = [1, 2, 3, 4, 5, -1]. The player stops at five steps and asks you to predict.
Dry run: Predict each step: a chain of six comments. The step-by-step player loads in your browser.
Reading without the player? Cover the last columns and predict them row by row.
| Step | Call that runs | Frames open | Returns |
|---|---|---|---|
| 1 | chain_length(0) | 1 | waiting |
| 2 | chain_length(1) | 2 | waiting |
| 3 | chain_length(2) | 3 | waiting |
| 4 | chain_length(3) | 4 | waiting |
| 5 | chain_length(4) | 5 | waiting |
| 6 | chain_length(5): the base case | 6 | 1 |
| 7 | chain_length(4) resumes | 5 | 2 |
| 8 | chain_length(3) resumes | 4 | 3 |
| 9 | chain_length(2) resumes | 3 | 4 |
| 10 | chain_length(1) resumes | 2 | 5 |
| 11 | chain_length(0) resumes | 1 | 6 |
The stack grows to six frames and then shrinks to none. The values 1, 2, 3, 4, 5 and 6 come back in the reverse order of the calls.
The largest number of frames open at once is the recursion depth. Here it is 6, one for each comment. The depth, and not the number of calls, is what hits the limit.
A recursion does not always go as deep as it makes calls. A function that halves its input in each call makes about log2 n calls in a row, so it is only 20 frames deep for n = 1,000,000. That is why the same lesson shows both cases.
Predict the frames
Q A function counts the comments in a chain and calls itself once for each comment. The chain has 8 comments. How many frames are open at the deepest point?
Answer: C
The first call cannot return until the last one has. At the deepest point, all 8 calls are open at once, and each one has its own frame.
Here is the rule that keeps a recursion correct. Every line of the template exists to protect it.
Each open call waits for one smaller call, and the base case returns at once, so answers are built as frames return, newest first.
A call is correct when two things hold. The recursive case moves the input toward the base case, and the base case gives the right answer. Then every call returns the right answer for its own input, by induction from the base case upward.
Here the input is the position in the chain. Each step moves one comment closer to the end, and the chain is finite, so the base case is reached. A chain that loops back on itself breaks the first rule, as the next section shows.
Use it when a question about an input can be answered from the same question about a smaller input. Signal words: the same question on a smaller input, a function that calls itself, a base case.
Base case: the smallest input, answered at once. Write it first.
Recursive case: call the same function on a smaller input, and trust that it returns the right answer. Combine that answer with this call's own part.
Progress: every call must move toward the base case.
Cost: one frame for each open call. The time is the number of calls, and the extra space is the recursion depth.
def chain_length(replies, start):
# [1] Base case: a comment with no reply ends the chain, so it counts for 1.
if replies[start] == -1:
return 1
# [2] Recursive case: ask the same question about the reply, which is one comment closer to the end.
below = chain_length(replies, replies[start])
# [3] Return: this comment plus everything below it.
return 1 + belowpublic int chainLength(int[] replies, int start) {
// [1] Base case: a comment with no reply ends the chain, so it counts for 1.
if (replies[start] == -1) {
return 1;
}
// [2] Recursive case: ask the same question about the reply, which is one comment closer to the end.
int below = chainLength(replies, replies[start]);
// [3] Return: this comment plus everything below it.
return 1 + below;
}int chainLength(vector<int>& replies, int start) {
// [1] Base case: a comment with no reply ends the chain, so it counts for 1.
if (replies[start] == -1) {
return 1;
}
// [2] Recursive case: ask the same question about the reply, which is one comment closer to the end.
int below = chainLength(replies, replies[start]);
// [3] Return: this comment plus everything below it.
return 1 + below;
}function chainLength(replies, start) {
// [1] Base case: a comment with no reply ends the chain, so it counts for 1.
if (replies[start] === -1) {
return 1;
}
// [2] Recursive case: ask the same question about the reply, which is one comment closer to the end.
const below = chainLength(replies, replies[start]);
// [3] Return: this comment plus everything below it.
return 1 + below;
}Rebuild the template: put its lines back in order. Loads in your browser.
Three markers: the base case, the recursive call, and the return that adds this comment.
The recursion adds one on the way back. A loop adds one on the way forward. The base case becomes the loop condition, and the frames become two variables.
def chain_length_loop(replies, start):
# [1] The comment being looked at, and the count so far: the start comment counts for 1.
current = start
total = 1
# [2] While the comment has a reply, move to it. This is the recursive case, with no new frame.
while replies[current] != -1:
current = replies[current]
# [3] Each reply adds one comment to the count.
total += 1
# [4] No reply is left: this is the base case, and the count is the length of the chain.
return totalpublic int chainLengthLoop(int[] replies, int start) {
// [1] The comment being looked at, and the count so far: the start comment counts for 1.
int current = start;
int total = 1;
// [2] While the comment has a reply, move to it. This is the recursive case, with no new frame.
while (replies[current] != -1) {
current = replies[current];
// [3] Each reply adds one comment to the count.
total++;
}
// [4] No reply is left: this is the base case, and the count is the length of the chain.
return total;
}int chainLengthLoop(vector<int>& replies, int start) {
// [1] The comment being looked at, and the count so far: the start comment counts for 1.
int current = start;
int total = 1;
// [2] While the comment has a reply, move to it. This is the recursive case, with no new frame.
while (replies[current] != -1) {
current = replies[current];
// [3] Each reply adds one comment to the count.
total++;
}
// [4] No reply is left: this is the base case, and the count is the length of the chain.
return total;
}function chainLengthLoop(replies, start) {
// [1] The comment being looked at, and the count so far: the start comment counts for 1.
let current = start;
let total = 1;
// [2] While the comment has a reply, move to it. This is the recursive case, with no new frame.
while (replies[current] !== -1) {
current = replies[current];
// [3] Each reply adds one comment to the count.
total++;
}
// [4] No reply is left: this is the base case, and the count is the length of the chain.
return total;
}Exercise · Put it in order: The chain as a loop. Arrange the lines into the loop version: it returns how many comments are in the chain from the start comment, with no recursion.
def chain_length(replies, start):
current = start
total = 1
while replies[current] != -1:
current = replies[current]
total += 1
return total
total = 0
while current != -1:The loop works because the recursive call is the last thing the function does, apart from adding one. Such a call is a tail call, and it can always become a loop. A recursion that must combine two answers, such as a tree, cannot be rewritten as easily, and needs a stack of your own.
A launch page shows show(s): it prints s, then calls show(s - 1), and it stops when s is 0. How many frames does show(5) need, and what does a loop need?
The base case is s == 0, and each call moves one step toward it. The calls are show(5), show(4), down to show(0): six frames are open at the deepest point, because show(0) is the base case and still has a frame.
| Step | Call | Frames open |
|---|---|---|
| 1 | show(5) | 1 |
| 2 | show(4) | 2 |
| 3 | show(3) | 3 |
| 4 | show(2) | 4 |
| 5 | show(1) | 5 |
| 6 | show(0), the base case | 6 |
A loop while s >= 0: print(s); s -= 1 needs one frame in all. For a start of 1,000, the recursion in Python fails, and the loop does not.
Each frame takes memory, and the call stack has a fixed size. Python protects itself with a counter: after about 1,000 open calls it raises a RecursionError. Other languages let the stack fill up instead, and then stop with an error such as StackOverflowError in Java.
The limit depends on the language and on the size of each frame. In one test run on a laptop, the reply-chain function reached between 6,500 and 7,200 frames in Node 22, and about 82,000 frames in Java 23. Treat these as rough. The safe rule is about the input: if the depth can grow with the input, plan for a loop.
Python lets you raise the limit with sys.setrecursionlimit. That hides the problem on your machine, and it does not help in the languages that have no such switch. A loop is the same everywhere.
Real production data brings edge cases.
For replies = [-1] and start = 0, the first call is the base case. It returns 1, and only one frame is ever open.
For replies = [2, 4, 1, -1, -1] and start = 2, the chain is 2, 1, 4. The function returns 3. A start in the middle of a chain counts only the comments after it, and the comment itself.
For the same list and start = 3, comment 3 has no reply, so the answer is 1. Comment 3 is not part of the chain from comment 0, and the chain from comment 0 does not change.
In a plain Python 3.11 script, a chain of 999 comments returns 999, and a chain of 1,000 raises RecursionError. One more comment crosses the limit. Test the largest input the product allows, not only a few comments.
This version trusts that the data always reaches a comment with no reply. The base case is correct, but the chain never reaches it.
Counterexample: replies = [1, 2, 0]. Comment 0 is answered by 1, comment 1 by 2, and comment 2 by 0. The calls go round the loop, and Python stops with RecursionError: maximum recursion depth exceeded.
A recursion needs progress toward the base case, and bad data can break it. Check the data, or count the calls and stop at a limit.
Data that loops back never reaches the base case, so the frames pile up until Python stops the program.
This version makes the recursive call and stores the answer in below, but it never returns 1 + below.
Counterexample: replies = [1, -1] and start = 0. The function returns None, not 2. Comment 1 returns 1 correctly, but comment 0 receives it and returns nothing.
Every path through the function must return a value. The values travel back only if every frame passes them on.
This version returns 0 in the base case, to count the links between comments, and not the comments.
Counterexample: replies = [2, 4, 1, -1, -1] and start = 0. It returns 3, and the correct count is 4. The header would show one comment too few.
The base case must give the right answer for the smallest input. Here the smallest chain is one comment, and its length is 1.
Your team lead asks for the length of a chain of 50,000 comments in Python. The recursion needs 50,000 frames, and the default limit is about 1,000, so it stops with a RecursionError.
Recursion is still the right way to think about the question. It is not the right way to run it here. Write the loop of Template 2: it keeps the base case and the step, and it uses one frame. A depth that grows with the input is the signal to convert.
Your team lead brings four product changes. Each one asks how deep the calls go.
Real threads branch: a comment can have many replies. The count is 1 plus the counts of all its replies. The recursion is as deep as the longest chain. A wide tree of 100,000 comments is safe, and a chain is not (LeetCode 104: Maximum Depth of Binary Tree uses the same shape).
A moderation tool must reverse a chain of replies. The recursive version reverses the rest of the chain, then fixes the link of the current comment. The frames hold each comment while the rest is reversed (LeetCode 206: Reverse Linked List).
A function that calls itself twice, such as the Fibonacci numbers, keeps only one branch open at a time. Its depth is n, and its number of calls is far larger. The next lesson counts those calls (LeetCode 509: Fibonacci Number).
The app shows only the first 200 levels of a thread. Pass the depth as a second argument and stop at 200. The depth is now bounded, and so is the stack.
Exercise · Find the bug: One comment too many. The thread view shows at most `cap` comments of a chain, so this returns the smaller of the chain length and `cap`. On a long chain it shows one comment too many. Which line is wrong?
def capped_length(replies, start, cap):
if cap == 0 or replies[start] == -1:
return 1
return 1 + capped_length(replies, replies[start], cap - 1)Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate what the call stack holds when a function calls itself, and why a very long chain stops it. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have built it.
A recursive function needs a base case that answers at once and a recursive case that calls itself on a smaller input. Each call gets a frame, and a waiting call keeps its frame until the call above it returns.
The base case returns first, and the values come back through the frames in the reverse order of the calls. The stack holds one frame for each open call, so the depth is the number of calls in a row.
When the depth grows with the input, the stack hits its limit. I keep the same logic in a loop.
A recursive function solves a question by asking the same question about a smaller input. It needs two parts: a base case that returns at once, and a recursive case that makes progress toward it.
Each call gets a frame on the call stack with its own variables. A call that is waiting keeps its frame, and the newest call is on top. The base case returns first. Each frame then receives the value from the frame above it, so values come back from the newest call to the oldest.
The cost is one frame for each open call. For a chain of n items, the depth is n, and Python stops at about 1,000 frames with a RecursionError.
So when the depth can grow with the input, I write the same logic as a loop, or with my own stack.
Checkpoint · The idea
Q1/3 What does the base case of a recursive function do?
Answer: B
The base case is the call that does not call again. Without it, or without progress toward it, the calls never stop.
Q2/3 A function calls itself once for each comment in a chain of 8 comments. How many frames are open at the deepest point?
Answer: C
The first call cannot return until the last one has, so all 8 calls are open at once. Each one has its own frame.
Q3/3 Which call returns first in a recursion that counts a chain?
Answer: B
A frame leaves the stack only when its call returns, and the newest frame is on top. The base case returns first, and the oldest call returns last.
Checkpoint · The values
Q1/3 A chain has 4 comments. The last call returns 1. What does the call right below it return, if each call returns 1 plus the value below it?
Answer: B
The call below receives 1, adds one for its own comment and returns 2. The values count up as they come back: 1, 2, 3, 4.
Q2/3 A recursive function makes the call and stores the answer in below, but it ends with no return of 1 + below. What does the caller get?
Answer: C
The values travel back only if every frame returns them. A frame that stores the value and does not return it loses the answer.
Q3/3 The data holds replies = [1, 2, 0], so comment 2 is answered by comment 0. What does the recursive count do?
Answer: B
No comment has the reply -1, so the base case is never reached. Each call opens a frame until the limit stops the program.
Checkpoint · The depth
Q1/4 In Python with the default settings, what happens when a recursion needs 1,500 frames open at once?
Answer: B
Python counts the open calls and stops at about 1,000 by default. There is no partial answer.
Q2/4 A function halves its input in each call and stops at 1. Its input is 1,000,000. About how many frames are open at the deepest point?
Answer: C
Halving 1,000,000 reaches 1 after about 20 steps, so about 20 frames are open. The depth follows the length of the chain of calls, and a halving chain is short.
Q3/4 A chain of 50,000 comments must be counted in Python. What is the best change?
Answer: B
A loop keeps one frame, so the depth no longer grows with the input. Raising the limit hides the problem, and it does not exist in every language.
Q4/4 Why can the reply-chain recursion turn into a loop so easily?
Answer: C
A call that is the last step is a tail call, so a loop that moves forward and adds one gives the same answer as the frames adding one on the way back.
Ten questions on this lesson. Pass with 80% or more to be sure the idea has landed before the next lesson.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Countdown of a launch timer | Stream | Easy | A base case, and a chain of a million calls replaced by a formula |
| 2 | Sum the digits of an order id | Shop | Easy | A number split into its last digit and the rest, and a shallow recursion |
| 3 | Print the call order | Platform | Easy | Reading the stack at one line of a very long log |
| 4 | Depth of nested folders | Platform | Medium | A recursion that is too deep, replaced by a stack of your own |
| 5 | Move a tower of crates between three bays | Freight | Medium | A recursive plan with two halves, read one move at a time |
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.