Recursion
How recursive functions work, how the call stack tracks them, when recursion repeats work or runs out of stack, and what interviewers ask about it.
On this page
Recursion means that a function solves a problem by calling itself on a smaller piece of the same problem. It is the natural way to process data that is nested to an unknown depth, such as folders inside folders, trees and JSON, and it is the basis of divide and conquer, backtracking and dynamic programming.
Without recursion, a loop over nested data needs one loop for each level of nesting, and you cannot write that when the depth is not known in advance. A recursive function handles any depth with the same few lines.
How a recursive function works
Every recursive function has two parts. The base case is an input small enough to answer directly, without another call. The recursive case splits the input into smaller pieces, calls the function on each piece, and combines the answers. The base case is what stops the calls, so every recursive call must work on something strictly closer to it than the current input is.
As an example, take a folder represented as a list whose items are either files (strings) or folders (lists). The list ["a", ["b", "c"], "d"] is two files plus a subfolder holding two more files. The number of files in a folder is the sum of the file counts of its items, and a single file counts as 1. That sentence is already the whole algorithm: the base case is a file, and the recursive case is a folder.
Tracing the call stack
When a function calls another function, the computer pauses the first one, remembers where it stopped and what its variables held, and runs the new call. When the new call returns, the paused one continues from the same place. The paused calls wait in the call stack, where the newest call is on top and only the top call runs. Each call has its own copy of its variables, so a folder's running total is never mixed up with its parent's.
The trace below follows countFiles(["a", ["b", "c"], "d"]). The first row is the call stack with the oldest call on the left, and the second row is the folder whose items are being counted.
countFiles(item): if item is a file: return 1 total = 0 for each child in item: total += countFiles(child) return total- call stack0rootroot0a1[b, c]2d
- root total
- 0
- calls so far
- 1
1The first call is on the whole folder, called root. It is a folder, so its total starts at 0.
- call stack0root1aroot0achild1[b, c]2d
- root total
- 0
- calls so far
- 2
2Root pauses and calls
countFiles("a"). The new call goes on top of the stack. - call stack0root1aroot0achild1[b, c]2d
- root total
- 0
- returned
- 1
- calls so far
- 2
3The item
"a"is a file, so this is the base case and the call returns 1. - call stack0rootroot0achild1[b, c]2d
- root total
- 1
- calls so far
- 2
4The call for
"a"leaves the stack, and root continues from where it paused and adds the 1 to its total. - call stack0root1[b, c][b, c]0b1c
- root total
- 1
- [b, c] total
- 0
- calls so far
- 3
5The next child is a folder, so root pauses and calls
countFiles([b, c]), which starts its own total at 0. - call stack0root1[b, c]2b[b, c]0bchild1c
- root total
- 1
- [b, c] total
- 0
- calls so far
- 4
6The call on
[b, c]pauses and callscountFiles("b"). Three calls are on the stack, and only the top one runs. - call stack0root1[b, c][b, c]0bchild1c
- root total
- 1
- [b, c] total
- 1
- calls so far
- 4
7The call for
"b"returns 1, and the call on[b, c]adds it to its own total. Root's total does not change. - call stack0root1[b, c]2c[b, c]0b1cchild
- root total
- 1
- [b, c] total
- 1
- calls so far
- 5
8The call on
[b, c]pauses again and callscountFiles("c"). - call stack0root1[b, c][b, c]0b1cchild
- root total
- 1
- [b, c] total
- 2
- calls so far
- 5
9The call for
"c"returns 1, so the total for[b, c]is now 2. - call stack0rootroot0a1[b, c]child2d
- root total
- 3
- returned
- 2
- calls so far
- 5
10The call on
[b, c]has no more children and returns 2. Root adds it to its total, which becomes 1 + 2 = 3. - call stack0root1droot0a1[b, c]2dchild
- root total
- 3
- calls so far
- 6
11Root pauses and calls
countFiles("d"). - call stack0rootroot0a1[b, c]2dchild
- root total
- 4
- calls so far
- 6
12The call for
"d"returns 1, so root's total becomes 4. - call stackroot0a1[b, c]2d
- answer
- 4
- calls
- 6
- tallest stack
- 3
13Root returns 4 and the stack is empty. The function made 6 calls, one for each file and folder, and the stack was never more than 3 calls tall.
The code
The function below is the same algorithm that the trace followed. An empty folder returns 0, because the loop does not run, and a folder is never asked about its grandchildren, because each child counts its own contents.
function countFiles(item) {
if (typeof item === "string") return 1; // base case: one file
let total = 0; // recursive case: a folder
for (const child of item) {
total += countFiles(child); // trust the smaller call
}
return total;
}
countFiles(["a", ["b", "c"], "d"]); // 4
countFiles(["a.jpg", ["b.jpg", ["c.jpg", []]], []]); // 3def count_files(item):
if isinstance(item, str):
return 1 # base case: one file
total = 0 # recursive case: a folder
for child in item:
total += count_files(child) # trust the smaller call
return total
count_files(["a", ["b", "c"], "d"]) # 4
count_files(["a.jpg", ["b.jpg", ["c.jpg", []]], []]) # 3Cost of recursion
The time is the number of calls multiplied by the work done in each call. Here every file and folder gets exactly one call. The memory is the height of the call stack at its tallest, because every paused call keeps its variables. Recursion therefore uses memory in proportion to the depth of the calls, even when the code never creates a list.
n is the number of files and folders, with one call for each. d is the deepest nesting, which is the most calls that can be waiting on the stack at once.
Variants of recursion
One recursive call on a smaller input
The simplest shape is a function that makes a single call on an input one step smaller, such as sum(nums, i) returning nums[i] + sum(nums, i + 1) or a factorial. The calls form a chain, so the time is O(n) and the stack is n calls tall. This shape is almost never the right choice in practice, because the same job is a plain loop that uses O(1) memory. It is mainly useful for learning how the stack works, and for linked lists, where it lets you act on the nodes in reverse order.
Several calls on non-overlapping pieces
The file counter is of this kind: each call splits its input into pieces that share nothing, and the total work is proportional to the input size. Merge sort and tree traversals also have this shape. The stack height equals the depth of the splitting, which is only about log n when each call cuts its input in half, and can be as large as n when the splits are very uneven, for example in a tree that is really a long chain.
Cutting the problem in half with one call
Some problems can discard half of the input at each step, so only one recursive call is needed. Computing x to the power n is the standard example: compute the power for n / 2 (rounded down), square the result, and multiply by one more x if n is odd. Finding 2 to the power 10 takes the calls for 10, 5, 2, 1 and 0, which is 5 calls instead of the 10 multiplications of a loop. The depth is O(log n), so both time and stack stay small. Binary search written recursively is the same idea.
Overlapping calls
Some problems split into pieces that overlap, and plain recursion then repeats work. The Fibonacci sequence 0, 1, 1, 2, 3, 5, 8 is the standard example, because each number is the sum of the two before it. In code, fib(n) = fib(n - 1) + fib(n - 2), with base cases fib(0) = 0 and fib(1) = 1. The formula is correct, but the calls recompute the same values many times.
Each call that is not a base case makes two more calls, so adding 1 to n multiplies the number of calls by about 1.6. Computing fib(30) this way makes 2,692,537 calls, almost all of them repeats. The fix is to store each answer the first time it is computed and to return the stored answer afterwards, which is called memoization and is the starting point of dynamic programming.
function fib(n, memo = new Map()) {
if (n < 2) return n; // base cases: fib(0) = 0, fib(1) = 1
if (memo.has(n)) return memo.get(n); // already computed
const result = fib(n - 1, memo) + fib(n - 2, memo);
memo.set(n, result);
return result;
}def fib(n, memo=None):
if memo is None:
memo = {}
if n < 2:
return n # base cases: fib(0) = 0, fib(1) = 1
if n in memo:
return memo[n] # already computed
memo[n] = fib(n - 1, memo) + fib(n - 2, memo)
return memo[n]| Approach | Time | Space | Why |
|---|---|---|---|
| Count files | O(n) | O(d) | Each item is visited once, and the pieces never overlap. |
| Naive Fibonacci | O(2ⁿ) | O(n) | The same values are recomputed many times. The true growth is about 1.6ⁿ, and 2ⁿ is the simple upper bound that people quote. |
| Memoized Fibonacci | O(n) | O(n) | Each value from 0 to n is computed once, and the stack is n calls deep. |
When a loop is the better tool
Anything recursive can be rewritten as a loop that keeps its own stack, so the choice is about clarity and limits. Use recursion when the data is nested, as with folders, trees and JSON, because the code then mirrors the data. Use it when the problem splits into smaller copies, as in divide and conquer, or when you try choices one at a time and undo them, as in backtracking. Use a loop for a flat walk over a list. Summing 100,000 numbers recursively leaves 100,000 calls waiting, and Python stops a program at a depth of about 1,000 calls by default.
Pitfalls
In the interview
Recursion is rarely the topic of a whole question. It appears as the tool for a tree, a nested structure, or a problem that asks for all combinations, all permutations or all paths. Signs that a problem calls for it are an input described as nested or as a tree, a statement that says "for every way to" or "find all", and a task that becomes the same task on a smaller input once one decision is made.
When you write the solution, say the base case and the recursive case aloud before coding, and state what the function returns for the smaller input. Interviewers watch for a correct base case, including the empty input, and for a clear statement of what each call is responsible for. These are the follow-up questions that come up most often.
What is the time and space complexity?
Count the calls and multiply by the work in each call. For space, give the maximum depth of the call stack, plus anything the function allocates. Saying "O(1) space" for a recursive solution is wrong unless the depth is constant.
What happens on a very deep input, and what do you do about it?
The program overflows the stack, which is a crash in JavaScript and a RecursionError in Python. You can rewrite the function as a loop with an explicit stack that you manage yourself, which moves the limit from the call stack to the heap. For some problems a different approach, such as a breadth-first traversal, avoids deep nesting.
Can you make this iterative?
Yes. Create a stack, push the starting input, and loop while the stack is not empty: pop an item, handle it, and push the smaller pieces that the recursive calls would have received. For a function that does work after its calls return, such as adding up the children's answers, you need to record which items are still waiting, which is why the iterative version is harder to write.
Why is this slow, and how do you speed it up?
Look for the same call with the same arguments happening more than once, as in Fibonacci. If that is the problem, add a memo table keyed by the arguments, which turns exponential time into a time proportional to the number of distinct arguments. If the calls never repeat, the recursion is already as fast as it can be and the cost lies elsewhere.
Does tail recursion help?
A tail call is a recursive call that is the very last thing the function does. Some languages reuse the current stack frame for it, so the depth does not grow. Python does not do this, and most JavaScript engines do not either, so in an interview a tail-recursive function still uses O(n) stack and is still a candidate for a loop.
How many calls does countFiles([["x"], "y"]) make in total, including the first one?
A recursive sum(nums, i) returns nums[i] + sum(nums, i + 1) and has no base case. What happens on [1, 2, 3]?
A folder structure is 10 levels deep and holds 5,000 files in total. Roughly how many calls of countFiles are waiting on the stack at the busiest moment?
Naive recursive fib(n) takes exponential time. What is the most direct fix?
What to practise next
To practise recursion now, solve Moving the Wedding Cake, which takes a few lines of recursion and is awkward as a plain loop. After that, Tree Traversals applies the folder pattern to trees, and Backtracking uses it to try every combination.