Recursion shows up in almost every coding interview, and it sits behind trees, DFS, merge sort and backtracking. If a function that calls itself has ever felt like a magic trick, this helper post is for you. Keep it open while you work through the Tekraze DSA series.
No heavy theory here. Just a full walk through of fact(4) on the call stack, three tricks that make recursion click, and working examples in Java, Python and Rust. For the time and space numbers below, keep the Big O helper post in a tab as well.
Also Read: DSA Series Helper: Time and Space Complexity Explained Simply (With Java, Python and Rust Examples) pairs with this page whenever you need to cost a recursion tree.
What is recursion in simple words?
Recursion is a function calling itself on a smaller version of the same problem. You do not solve the full problem in one go. You peel off one piece, ask the same function to solve what is left, and combine that result with the piece you kept.
A loop stays inside one function and repeats a block of code. Recursion starts a fresh call, with its own arguments and local variables, and that call can start another one.
What are the base case and the recursive case?
Every correct recursive function has two parts. The base case is the smallest input you can answer immediately, with no further call. For factorial, that is n <= 1, which returns 1, because 0! and 1! are both 1. For a sum over an array, the empty remaining slice returns 0.
The recursive case is everything else. You shrink the input, call the same function, and use that result. For factorial, you return n * fact(n - 1). The n - 1 is the shrink. Without it, the function would call itself forever. The base case stops the chain, and the recursive case must move toward that stop.
What happens on the call stack for fact(4)?
The call stack is the list of function calls that have started but not finished. Each call gets a frame that holds its own n and the line it is waiting on. Once you walk through fact(4), most recursive functions start to look the same.
First the calls go down.
fact(4)starts and needs4 * fact(3). It pauses and waits.fact(3)starts and needs3 * fact(2). It pauses and waits.fact(2)starts and needs2 * fact(1). It pauses and waits.fact(1)hits the base case and returns 1 immediately.
Then the answers come back up.
fact(2)resumes and returns2 * 1 = 2.fact(3)resumes and returns3 * 2 = 6.fact(4)resumes and returns4 * 6 = 24.
A compact picture of the same walk:
fact(4)
└─ fact(3)
└─ fact(2)
└─ fact(1) → 1
← 2 * 1 = 2
← 3 * 2 = 6
← 4 * 6 = 24
| Phase | Call | What it does | Value |
|---|---|---|---|
| Going down | fact(4) | Waits for fact(3) | — |
| Going down | fact(3) | Waits for fact(2) | — |
| Going down | fact(2) | Waits for fact(1) | — |
| Base case | fact(1) | Returns immediately | 1 |
| Coming back | fact(2) | 2 × 1 | 2 |
| Coming back | fact(3) | 3 × 2 | 6 |
| Coming back | fact(4) | 4 × 6 | 24 |
Only one path lives on the stack at a time. When fact(1) returns, its frame is gone before fact(2) finishes. That is why naive recursive Fibonacci is exponential in time but only linear in stack space: the tree of calls is huge, but you only hold one path from the first call down to a base case.
Why does recursion cause a stack overflow?
Every pending call costs memory. If the chain never hits a base case, or if it is simply too deep for the runtime, the stack runs out and the program crashes. In Python you usually see RecursionError after about 1,000 nested calls, because sys.getrecursionlimit() defaults to 1,000. In Java you get a StackOverflowError. In Rust the process typically aborts when the thread stack is exhausted.
Two things cause this in practice: a missing or unreachable base case, or a problem that is genuinely deep, like recursing once per element on an array of a million items. For deep linear work, a loop is safer. Recursion fits better when the depth stays closer to the height of a tree, often O(log n) when the tree is balanced, or when the input is small, as in many backtracking problems.
What are the 3 tricks that make recursion click?
Trick 1: Write the base case first
Before you think about the recursive call, write the condition that stops. If there is no base case, you are one typo away from a stack overflow. For factorial, start with if n <= 1: return 1. For a tree, start with if node is None: return. Get that line right, then write the rest.
Trick 2: Trust that the smaller call works
Once the base case is in place, assume fact(n - 1) already returns the correct factorial. Your only job is to combine it with n. You do not need to mentally expand fact(3), fact(2) and fact(1) every time. After you have walked one example like fact(4), trust the smaller call and write the combination step.
Trick 3: Shrink every call toward the base case
Every recursive call must make the input smaller, closer to the base case. fact(n) calls fact(n - 1). A tree walk calls the left and right children. An array sum advances the index by one. If a call uses the same argument, or moves away from the base case, the chain never ends. After you write a function, ask: will this argument eventually satisfy the base case? If you cannot answer yes, fix the shrink before you run anything.
What do recursion examples look like in Java, Python and Rust?
The snippets below are the same three problems in each language: factorial, Fibonacci (naive and memoized), and the sum of an array. I compiled and ran them before putting them here. fact(4) prints 24, fib(10) prints 55, and the sum of [1, 2, 3, 4, 5] prints 15.
Factorial, Fibonacci and array sum in Java
import java.util.HashMap;
import java.util.Map;
public class RecursionExamples {
// O(n) time, O(n) stack space
static int fact(int n) {
if (n <= 1) {
return 1;
}
return n * fact(n - 1);
}
// O(2^n) time, O(n) stack space
static int fib(int n) {
if (n < 2) {
return n;
}
return fib(n - 1) + fib(n - 2);
}
// O(n) time, O(n) space thanks to memo
static int fibMemo(int n) {
return fibMemo(n, new HashMap<>());
}
static int fibMemo(int n, Map<Integer, Integer> memo) {
if (n < 2) {
return n;
}
if (memo.containsKey(n)) {
return memo.get(n);
}
int value = fibMemo(n - 1, memo) + fibMemo(n - 2, memo);
memo.put(n, value);
return value;
}
// O(n) time, O(n) stack space
static int arraySum(int[] nums, int i) {
if (i == nums.length) {
return 0;
}
return nums[i] + arraySum(nums, i + 1);
}
public static void main(String[] args) {
System.out.println(fact(4));
System.out.println(fib(10) + " " + fibMemo(10));
System.out.println(arraySum(new int[]{1, 2, 3, 4, 5}, 0));
}
}
Naive Fibonacci is here so you can see the two recursive calls. That is the expensive tree. The memoized version stores each n the first time you compute it, so later calls return in constant time. Memoization turns O(2n) into O(n). The same idea shows up in the Big O helper post.
The same recursion examples in Python
# O(n) time, O(n) stack space
def fact(n):
if n <= 1:
return 1
return n * fact(n - 1)
# O(2^n) time, O(n) stack space
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
# O(n) time, O(n) space thanks to memo
def fib_memo(n, memo=None):
memo = {} if memo is None else memo
if n < 2:
return n
if n not in memo:
memo[n] = fib_memo(n - 1, memo) + fib_memo(n - 2, memo)
return memo[n]
# O(n) time, O(n) stack space
def array_sum(nums, i=0):
if i == len(nums):
return 0
return nums[i] + array_sum(nums, i + 1)
print(fact(4))
print(fib(10), fib_memo(10))
print(array_sum([1, 2, 3, 4, 5]))
Watch the memo=None default. In Python, a default of memo={} would be shared across calls, which is a classic bug. Creating a new dict when memo is None keeps each top-level call clean.
The same recursion examples in Rust
use std::collections::HashMap;
// O(n) time, O(n) stack space
fn fact(n: u64) -> u64 {
if n <= 1 {
1
} else {
n * fact(n - 1)
}
}
// O(2^n) time, O(n) stack space
fn fib(n: u64) -> u64 {
if n < 2 {
n
} else {
fib(n - 1) + fib(n - 2)
}
}
// O(n) time, O(n) space thanks to memo
fn fib_memo(n: u64, memo: &mut HashMap<u64, u64>) -> u64 {
if n < 2 {
return n;
}
if let Some(&value) = memo.get(&n) {
return value;
}
let value = fib_memo(n - 1, memo) + fib_memo(n - 2, memo);
memo.insert(n, value);
value
}
// O(n) time, O(n) stack space
fn array_sum(nums: &[i32]) -> i32 {
match nums {
[] => 0,
[head, rest @ ..] => head + array_sum(rest),
}
}
fn main() {
println!("{}", fact(4));
println!("{} {}", fib(10), fib_memo(10, &mut HashMap::new()));
println!("{}", array_sum(&[1, 2, 3, 4, 5]));
}
Rust makes the memo map explicit with a mutable reference, so there is no default-argument trap. The array sum uses a slice pattern: the empty slice is the base case, and the rest of the slice is the smaller problem. A reverse-a-string function follows the same shape, but concatenation and slicing can hide extra O(n) work per call and make the total time O(n²). For a real string, two pointers are usually better. For a linked list, the recursive shape is natural, which is why DSA Series Day 18: Reverse Linked List in Java, Python and Rust is a good next practice problem.
When should you use recursion vs iteration?
| Aspect | Recursion | Iteration |
|---|---|---|
| How it works | The function calls itself on a smaller input | A loop repeats a block inside one call |
| Extra memory | O(depth) on the call stack | Usually O(1) extra |
| Readability | Natural for trees, DFS, backtracking and divide and conquer | Natural for linear scans |
| Failure mode | Stack overflow if the depth is huge or the base case is missing | Usually safer for deep linear work |
| Best fit | Trees, graphs (DFS), merge sort, backtracking | Arrays, tight loops, very large n |
There is no single winner. If the data is a tree or a graph, recursion (or an explicit stack that mimics it) usually matches the structure. If you are scanning an array and the depth would be n, a loop is the default. You can write binary search either way. The loop version in DSA Series Day 23: Binary Search in Java, Python and Rust avoids extra stack frames, and the recursive version is a clean teaching example of “shrink the range and call again.”
What is the time and space complexity of recursion?
To get the time complexity, draw the recursion tree, count the calls, and multiply by the work inside one call, ignoring the recursive call itself. To get the space complexity, look at the deepest path, plus any data you store, such as a memo map.
| Example | Time | Extra space | Why |
|---|---|---|---|
| Factorial | O(n) | O(n) stack | One call per integer down to 1 |
| Array sum | O(n) | O(n) stack | One call per element |
| Naive Fibonacci | O(2ⁿ) | O(n) stack | Two calls per step, no sharing |
| Memoized Fibonacci | O(n) | O(n) memo + stack | Each n is computed once |
| Recursive binary search | O(log n) | O(log n) stack | Input halves each time |
| Merge sort | O(n log n) | O(n) plus O(log n) stack | log n levels, O(n) work per level |
A useful rule: two recursive calls and no memo usually means exponential time. One recursive call that shrinks the input by one is O(n) time and O(n) stack space. Split in half each time, like binary search or a balanced tree walk, and the depth is O(log n). Merge sort has O(log n) levels and does O(n) work at each level, which is O(n log n) time. For the fuller rules, read the Big O helper post. And do not forget the stack when you state space. A recursive function that “allocates nothing” still uses O(depth) memory.
Where is recursion used in real problems?
- Trees. Almost every tree problem is “do something with this node, then recurse on the left and right child.” The base case is a null node. The Data Structures Cheat Sheet walks through binary trees and the standard walks.
- DFS. Depth-first search on a graph is recursion plus a visited set, or an explicit stack. You go as deep as you can, then backtrack. The same cheat sheet compares BFS and DFS.
- Merge sort. You split the array in half, sort each half recursively, then merge the two sorted halves. The merge step is the same idea as DSA Series Day 19: Merge Two Sorted Lists in Java, Python and Rust.
- Backtracking. Problems like subsets, permutations, combination sum and N-Queens build a partial answer, recurse, then undo the last choice.
- Recursive binary search is the same “halve and continue” idea as the loop. Use it as practice, then prefer the loop in Binary Search when you want O(1) extra space.
What common mistakes break recursive code?
- Forgetting the base case, or writing one that some inputs never reach.
- Not shrinking the input, so the function calls itself with the same argument and blows the stack.
- Off-by-one mistakes around 0 and 1, such as returning 1 for
fib(0)instead of 0. - Forgetting stack space when you quote complexity. Time can be O(n) while space is also O(n) because of the frames.
- Using naive recursion on Fibonacci or other overlapping subproblems, then being surprised by timeouts. Add memoization or switch to a loop.
- In Python, using a mutable default like
memo={}. Usememo=Noneand create a new dict inside. - In backtracking, forgetting to undo a choice after the recursive call, so later branches see dirty state.
- Recursing n levels deep on a huge array or linked list, then hitting a stack overflow when a loop would have been enough.
How will this helper fit the rest of the series?
Whenever a daily DSA post uses a recursive solution, this is the page to return to. Read it once, then try to write the base case, the shrink and the combination step before you look at the answer. For the structures recursion walks over, keep the Data Structures Cheat Sheet nearby. For the cost of each call tree, stay with the Big O helper. For a first problem that can be solved recursively or iteratively, start with Reverse Linked List or Binary Search.
Frequently asked questions
What is recursion in simple words?
Recursion is a function calling itself on a smaller version of the same problem, until a base case can be answered directly.
What is a base case and why do you need it?
The base case is the input you can return immediately, with no further recursive call. Without it, the calls never stop and the call stack overflows.
Why does fact(4) return 24?
The calls go down fact(4) to fact(3) to fact(2) to fact(1). The base case returns 1, then the answers come back up as 2×1=2, 3×2=6 and 4×6=24.
When should I use recursion instead of a loop?
Use recursion when the problem has a natural smaller subproblem, especially trees, DFS, merge sort and backtracking. Use a loop when you are scanning a linear structure and a deep call stack would be a risk.
Does recursion always use extra space?
Yes, in the usual implementation. Each pending call sits on the call stack, so depth d costs O(d) space even if you create no data structures. Some compilers can drop that cost for tail-recursive functions, but you should not rely on that in Java or Python interviews.





