Quick reference
Recursion is when a method solves a problem by calling itself on a smaller version of the same problem, over and over, until it reaches a case simple enough to answer directly. The answers to the smaller problems are then combined on the way back up.
Every recursive method has:
- A base case that returns an answer without recursing. It's what stops the recursion.
- A recursive case that calls the method on a smaller input and uses the result.
Keep in mind:
- Each call gets its own frame on the call stack, so recursion uses extra memory proportional to how deep the calls go. Recursing too deeply causes a stack overflow.
- Anything you can write recursively, you can also write with a loop (sometimes with an explicit stack), and vice versa.
- Recursion that solves the same subproblem many times can be sped up with memoization, which leads to dynamic programming.
Base Case and Recursive Case
Factorial is the classic example. "n factorial," written n!, is n × (n - 1) × ... × 2 × 1. So 4! = 4 × 3 × 2 × 1 = 24.
Notice that n! = n × (n - 1)!. The factorial of n is defined in terms of a smaller factorial, which makes it a natural fit for recursion:
-
The base case
is
n <= 1. We know 0! and 1! are both 1, so we return 1 without making another call. -
The recursive case is
n * factorial(n - 1). We trust that the smaller call returns the right answer, and do one step of work on top of it.
How to write a recursive method
- Decide exactly what the method returns for a given input. For example, "factorial(n) returns n!"
- Handle the smallest inputs directly. Those are your base cases.
- For bigger inputs, assume the method already works on smaller inputs, and use that to build the answer. This "leap of faith" is the key mental move: don't try to trace every call in your head.
-
Make sure every recursive call moves toward a base
case.
n - 1gets closer to 1, and a shorter array gets closer to empty. - Check how deep the recursion can go, since each level costs a stack frame.
Recursion on a data structure: summing an array
The same shape works on data. The sum of an array is its first number plus the sum of everything after it, and the sum of an empty array is 0:
Here the base case is "no numbers left," and each recursive call moves the start index one step closer to it.
Tracing Recursion on the Call Stack
To see what actually happens when a recursive
method runs, let's trace
factorial(4). Each call pushes a new frame onto the
call stack,
holding that call's own value of n. A call can't finish
until the call it made returns, so frames pile up on the way down and
come off one at a time on the way back up:
| Step | Call stack (top frame first) | What happens |
|---|---|---|
| 1 | factorial(4) | 4 isn't ≤ 1, so it needs 4 × factorial(3). It calls factorial(3) and waits. |
| 2 | factorial(3) factorial(4) |
Needs 3 × factorial(2). Calls factorial(2) and waits. |
| 3 | factorial(2) factorial(3) factorial(4) |
Needs 2 × factorial(1). Calls factorial(1) and waits. |
| 4 | factorial(1) factorial(2) factorial(3) factorial(4) |
Base case: returns 1. The stack is at its deepest: 4 frames. |
| 5 | factorial(2) factorial(3) factorial(4) |
Gets 1 back and returns 2 × 1 = 2. |
| 6 | factorial(3) factorial(4) |
Gets 2 back and returns 3 × 2 = 6. |
| 7 | factorial(4) | Gets 6 back and returns 4 × 6 = 24. |
| 8 | (empty) | The original caller gets 24. |
The first half (steps 1–4) is sometimes called "winding": the method keeps calling itself and nothing gets computed yet. The second half (steps 5–8) is "unwinding": each call finishes its multiplication and returns.
The stack got 4 frames deep for factorial(4), so
factorial(n) takes O(n) space,
even though it never creates a data structure. In general, recursion's
extra space is the maximum depth of the call stack, not
the total number of calls. A recursive Fibonacci
method makes an exponential number of calls, but
only about n of them are ever on the stack at once.
Recursion vs. Iteration
Here's factorial again, written with a loop instead:
| Recursion | Iteration | |
|---|---|---|
| How it repeats | The method calls itself | A for or while loop |
| When it stops | When it reaches a base case | When the loop condition becomes false |
| Extra memory | One stack frame per level, so space grows with the depth | None for the looping itself: O(1) |
| When it goes wrong | A missing base case or a too-deep input causes a stack overflow | A bad loop condition causes an infinite loop |
| Speed | Pays for a method call on every step | Usually a bit faster |
| Best for | Naturally recursive problems: trees, graphs, divide and conquer, backtracking | Straight-line repetition, and inputs that could make recursion too deep |
Any recursive algorithm can be rewritten iteratively by keeping your own stack (that's exactly how iterative depth-first search works), and any loop can be rewritten as recursion. In an interview, recursion is often the clearest first draft for tree and backtracking problems. Switch to a loop when the recursion could get very deep, like walking a linked list with a million nodes.
Common Recursion Pitfalls
-
A missing or unreachable base case. Without a base case, the method calls itself until it runs out of stack space. A base case can also be unreachable: if the base case is
n == 0and someone passes in a negative number, or if the recursive call doesn't actually shrink the input, you'll never hit it. (See base case.) -
Stack overflow on deep inputs. Even correct recursion fails if it goes too deep:
-
Python has a default recursion limit of
1,000 (
sys.getrecursionlimit()). Going past it raisesRecursionError: maximum recursion depth exceeded. You can raise the limit withsys.setrecursionlimit(), but every frame still costs memory, so for inputs that can get deep, a loop is the more robust fix. -
Java throws a
StackOverflowError. There's no fixed limit on the number of calls: it depends on the thread's stack size (set with-Xss) and how big each frame is. -
JavaScript throws
RangeError: Maximum call stack size exceeded. The limit depends on the engine and on the frame size. - C and C++ don't throw anything. The program usually just crashes, often with a segmentation fault.
For simple methods with default settings, Java and JavaScript typically run out somewhere in the thousands to tens of thousands of calls deep.
-
Python has a default recursion limit of
1,000 (
-
Repeated work. A method that makes more than one recursive call can end up solving the same subproblem over and over. A plain recursive Fibonacci method takes exponential time for exactly this reason. Saving each result the first time (memoization) fixes it, and is the first step toward dynamic programming.
-
Hidden copying. It's tempting to pass a slice of "the rest of the array" to each recursive call. But making that copy takes O(n) time, so summing an array that way takes O(n^2) time overall. Passing a start index, like the sum example above does, avoids the copies.
-
Forgetting to return the recursive result. Calling
factorial(n - 1)without returning (or using) its value is a common bug. The recursion runs, but the answer gets thrown away. -
Forgetting the call stack in your space complexity. A recursive depth-first traversal of a tree uses O(h) space for the call stack, where h is the tree's height, even if it doesn't allocate anything else.
Tail Recursion and Tail Call Optimization
A recursive call is a tail call if it's the very last
thing the method does: its result gets returned
as-is, with no more work after it. Our factorial isn't tail recursive,
because after factorial(n - 1) returns, it still has to
multiply by n. Passing the running product along in an
extra "accumulator" argument makes it tail recursive:
Since there's nothing left to do after a tail call, the current stack frame isn't needed anymore. A compiler or runtime that does tail call optimization (TCO) reuses that frame instead of pushing a new one, so tail-recursive code runs in O(1) stack space, just like a loop. But many mainstream languages don't do it:
| Language | Optimizes tail calls? |
|---|---|
| Python | No. The tail-recursive factorial above still hits the recursion limit. |
| Java | No. The JVM doesn't eliminate tail calls, so deep tail recursion still throws StackOverflowError. |
| JavaScript | In theory, yes: the ES2015 spec requires it in strict mode. In practice, only Safari's JavaScriptCore engine does it. V8 (Chrome and Node.js) and SpiderMonkey (Firefox) don't. |
| C and C++ | Not guaranteed by the language, but GCC and Clang usually do it with optimizations turned on (for example, -O2). |
| Ruby | Not by default. The standard interpreter has an opt-in compile option for it. |
| Kotlin | Yes, for functions marked tailrec: the compiler turns them into loops. |
| Scheme | Yes. The language standard requires it. |
So in an interview, don't count on tail call optimization. If the recursion could get deep, write it as a loop instead. A tail-recursive method is easy to convert: the accumulator becomes a local variable, and the tail call becomes the next trip through the loop.
Classic Recursive Patterns
Divide and conquer
Split the input into independent parts, solve each part recursively, and combine the results. Merge sort splits an array in half, sorts each half recursively, and merges them. Quicksort partitions around a pivot and recursively sorts each side. And binary search can recurse into whichever half could hold the target.
Tree and graph traversal
A tree is a recursive structure: each child of a node is the root of a smaller tree. So most tree algorithms handle the current node and then recurse on its children, with an empty tree as the base case. Pre-order, in-order, and post-order traversals of a binary tree differ only in whether you visit the node before, between, or after the recursive calls on its children. Depth-first search applies the same idea to graphs, using a visited set so it doesn't loop forever.
Practice: Balanced Binary Tree asks you to check whether all of a binary tree's leaves are at nearly the same depth.
Backtracking
Build a solution one choice at a time. At each step, try each option: make the choice, recurse to fill in the rest, then undo the choice and try the next one. If a partial solution can't possibly work, stop exploring it early. Generating all permutations or subsets, solving Sudoku, and placing N queens on a chessboard are all backtracking problems.
Practice: Recursive String Permutations asks you to write a recursive method that generates every permutation of a string.
Recursion with memoization (top-down dynamic programming)
When different branches of the recursion keep asking the same question, save each answer the first time you compute it and look it up after that. That's memoization, and it's the top-down form of dynamic programming. It can turn an exponential-time recursive solution into a polynomial-time one.
Practice: Compute the nth Fibonacci number, where the obvious recursive solution quickly spins out of control.
Recursion interview questions to practice
Each one walks you through a real coding interview problem one hint at a time.
- Recursive String Permutations » Write a recursive function of generating all permutations of an input string.
- Compute the nth Fibonacci Number » Computer the nth Fibonacci number. Careful--the recursion can quickly spin out of control!
Your first 3 questions are free. Just sign in, no credit card. More Recursion questions
See also:
Interview coming up?
Get the free 7-day email crash course. You'll learn how to think algorithmically, so you can break down tricky coding interview questions.
No prior computer science training necessary—we'll get you up to speed quickly, skipping all the overly academic stuff.
No spam. One-click unsubscribe whenever.
You're in! Head over to your email inbox right now to read day one!
Interview Cake