Recursion

A function that solves a problem by calling itself on a smaller version of the same problem.

What is it?

Some problems are defined by smaller versions of themselves: the total of a list, every folder inside a folder, a factorial. With recursion, a function calls itself on a smaller input until the input is simple enough to answer directly (the base case).

Every recursive function needs:

  • a base case that stops the recursion
  • a step that moves the problem toward that base case

Explain like I'm 10

Recursion is like Russian nesting dolls. You open each doll to find a smaller one inside, until you reach the smallest doll, which doesn't open. That smallest doll is the base case.

Examples

Factorial using recursion

function factorial(n) {
  if (n <= 1) return 1;       // base case
  return n * factorial(n - 1); // recursive case
}

console.log(factorial(4)); // 4 * 3 * 2 * 1 = 24

Each call reduces n by 1 and calls itself, until n reaches 1 (the base case). Then the calls return back up the chain.

How it works

Each recursive call goes on the call stack and waits for the call it made to return. Once the base case is reached, the calls finish in reverse order. Each one combines its result with what it got back, until the original call returns.

factorial(4)
  → 4 * factorial(3)
       → 3 * factorial(2)
            → 2 * factorial(1)
                 → returns 1 (base case)
            → returns 2 * 1 = 2
       → returns 3 * 2 = 6
  → returns 4 * 6 = 24

Why does it exist?

Some structures and problems are naturally recursive: folders inside folders, trees, some math definitions. Without recursion you need extra bookkeeping that the call stack otherwise handles for you.

When to use it

Use recursion when a problem is defined by a smaller version of itself: walking nested folders or a tree, or divide-and-conquer algorithms like merge sort.

When not to use it

For plain repetition (like summing a flat array), a loop is clearer and avoids piling calls on the stack. On very large inputs, too many nested calls can overflow the call stack.

Common mistakes

  • Forgetting the base case, so the recursion never stops and the program crashes ('stack overflow').

  • Writing a recursive case that doesn't move closer to the base case.

  • Using recursion where a simple loop would be clearer and more efficient.

Practice exercises

  1. Easy:

    Write a recursive function that sums all numbers from 1 to n.

  2. Medium:

    Write a recursive function that reverses a string.

  3. Hard:

    Write a recursive function that returns all subsets of a given array.

Interview questions

What two things does every recursive function need?

A base case that stops the recursion, and a recursive step that moves the input toward that base case.

What causes a 'stack overflow' in recursion?

Recursing too deeply (or forever, because of a missing or broken base case) fills the call stack past its limit.

When would you prefer recursion over a loop?

When the problem is recursive in shape, like trees, nested data or divide-and-conquer algorithms, where recursion reads more clearly than manual bookkeeping.

Trace `factorial(4)` step by step, showing both the 'calling down' and 'returning up' phases.

Calling down: factorial(4) calls factorial(3), which calls factorial(2), which calls factorial(1). That hits the base case and returns 1. Returning up: factorial(2) returns 2 * 1 = 2, factorial(3) returns 3 * 2 = 6, and factorial(4) returns 4 * 6 = 24.

What is the time and space complexity of the recursive factorial function, and where does the space cost come from?

O(n) time: n calls before the base case. O(n) space, from the call stack, not the values: each pending call waits on the stack, so n frames are alive at the deepest point.

Why does the iterative version of factorial only need O(1) extra space, while the recursive version needs O(n)?

The loop updates one running total and one counter in place. The recursive version keeps every pending frame (with its own n and pending multiplication) until deeper calls return, so memory grows with depth.

What is tail recursion, and does JavaScript automatically optimize it away like some other languages do?

A call is in tail position when it's the last thing the function does, with no work (like a multiplication) left afterwards. Engines with 'proper tail calls' reuse the current frame, making tail recursion O(1) stack space. ECMAScript 2015 includes proper tail calls, but most engines, including V8 (Chrome/Node.js), never shipped them; only Safari's JavaScriptCore does. So tail-recursive JavaScript does not reliably avoid stack growth.

Rewrite `factorial` to be tail-recursive using an accumulator parameter, and explain why the rewritten version qualifies as tail-recursive but the original doesn't.

function factorial(n, acc = 1) { if (n <= 1) return acc; return factorial(n - 1, n * acc); }. In the original (return n * factorial(n - 1)), the multiplication happens after the recursive call returns, so the call isn't the last action. The rewrite carries the product forward in acc and just returns the recursive call's result.

Given that most JavaScript engines don't implement proper tail calls, does making a function tail-recursive actually save it from stack overflow in Node.js?

No. In Node.js/V8 a tail call still pushes a new frame, so deep tail recursion can still overflow. The rewrite is cleaner and would be optimized on an engine that supports it (like Safari), but it's not a reliable fix in most JavaScript runtimes.

What is trampolining, and how does it let you simulate tail-call optimization manually in a language without it?

Each step returns a thunk (a zero-argument function for the next step) instead of calling itself. A driver loop (the 'trampoline') keeps calling the thunk it gets back until it receives a real value. Each step returns to the loop instead of recursing, so only one frame is ever on the stack.

What is memoization, and how does it change the time complexity of computing the nth Fibonacci number recursively?

Memoization caches each result by its input, so repeated calls return the cached value. Naive recursive Fibonacci recomputes the same subproblems (fib(5) calls fib(3) twice, fib(2) three times, and so on) and grows exponentially: usually quoted as O(2^n), with a tighter bound of O(φⁿ) ≈ O(1.618ⁿ). With memoization each fib(k) from 0 to n is computed once: O(n) time, plus O(n) space for the cache.

Why is naive recursive Fibonacci exponential, when the function only ever calls itself twice per invocation?

Each fib(n) calls fib(n-1) and fib(n-2), and each of those calls two more. The number of calls roughly doubles per level over about n levels: exponential (usually bounded as O(2^n)). Many calls repeat the same subproblem; fib(n-2) is reached directly from fib(n) and again via fib(n-1). That repeated work is what memoization removes.

What's the difference between 'linear recursion' (like factorial) and 'tree recursion' (like naive Fibonacci) in terms of the shape of the call graph, and how does that affect complexity?

Linear recursion makes one call per invocation, so the calls form a single chain of depth n, typically O(n) time. Tree recursion makes several calls per invocation, so the calls form a tree. The total grows with the tree's size, often exponentially, unless overlapping subproblems are memoized.

What is the recurrence relation for merge sort's time complexity, and what does it evaluate to?

T(n) = 2T(n/2) + O(n): recurse on two halves, then do O(n) work merging. By the Master Theorem, that's O(n log n).

What is the recurrence relation for a function like binary search's time complexity, and why does it resolve to O(log n) instead of O(n)?

T(n) = T(n/2) + O(1): constant work, then recurse into only one half and discard the other. n can be halved log₂(n) times before reaching 1, so it's O(log n). Merge sort recurses into both halves.

What is divide-and-conquer, and how does recursion make it a natural fit?

Split a problem into smaller subproblems of the same shape, solve each (usually recursively), and combine the results. The 'divide' step becomes recursive calls on smaller inputs, the base case is the smallest subproblem, and the call stack tracks pending work automatically.

Why is recursion a natural fit for traversing a tree, but breadth-first traversal is conventionally written iteratively with an explicit queue instead?

A tree is defined recursively (a node plus subtrees), so depth-first recursion (process this node, then each child) mirrors it, and the call stack tracks the path back up. Breadth-first visits nodes level by level across branches, not down one chain. It needs a FIFO queue of discovered nodes, which the LIFO call stack doesn't give you.

What is mutual (indirect) recursion? Give an example.

Two or more functions that call each other instead of themselves, until a base case stops the chain. Example: isEven(n) returns true if n === 0, else isOdd(n - 1); isOdd(n) returns false if n === 0, else isEven(n - 1).

What's the subtle bug in `function sum(arr) { if (arr.length === 0) return 0; sum(arr.slice(1)) + arr[0]; }`?

There's no return on the recursive line, so its value is computed and thrown away. For any non-empty array, the function returns undefined instead of the sum.

Roughly how many stack frames can a JavaScript call stack hold before overflowing, and what does that mean for recursion on very large inputs?

It varies by engine and stack memory, typically from a few thousand up to about ten-to-fifteen thousand frames for ordinary functions in Node.js/V8. Recursing once per element of, say, a million-element array overflows long before finishing, though a simple loop would handle it fine.

Why is a loop generally preferred over recursion for a simple 'do this for every item' task, even though both can technically solve it?

A loop uses O(1) extra stack space; recursion adds a frame per call (O(n)) and can overflow on large inputs. When the task is plain repetition, not 'a smaller version of the same problem', recursion adds that cost for no benefit.

How would you convert an iterative loop that accumulates a total into a recursive function producing the same result?

Pass the running total and current position as parameters and recurse forward: function sumFrom(arr, i = 0, total = 0) { if (i === arr.length) return total; return sumFrom(arr, i + 1, total + arr[i]); }. The base case is reaching the end of the array; the state travels as arguments instead of loop variables.

What is backtracking, and how does it relate to plain recursion?

Recursion with a rule: try a choice, recurse, and if it doesn't lead to a valid solution, undo it and try the next. It prunes branches that can't work instead of exploring the whole search tree. It's used for permutations, Sudoku and N-Queens.

What's the time complexity of a recursive function that generates all subsets of an n-element array, and why?

O(2^n). Each element is either in or out, so there are 2^n subsets, and you must produce them all. The recursion branches in two (include / exclude) at each of the n elements.

What's the time complexity of a recursive function that generates all permutations of an n-element array, and why is it worse than the subset-generation recursion?

O(n!), since there are n! orderings. At each of n levels the recursion branches into the remaining choices, not a fixed 2. n! grows far faster than 2^n, so permutations become intractable at sizes where subsets may still be feasible.

Why does recursion make sense for traversing nested folders/JSON but not for looping over a flat array of numbers?

Nested folders are self-similar: a folder holds files and more folders. Processing 'this folder, then each subfolder the same way' matches that shape, and the depth isn't known in advance. A flat array is just a sequence to step through once, so a loop already fits.

Trace the call tree for `fib(4)` under naive (non-memoized) recursion, and count how many times `fib(1)` gets computed.

fib(4) calls fib(3) and fib(2). fib(3) calls fib(2) and fib(1). That fib(2) calls fib(1) and fib(0). The fib(2) called directly from fib(4) also calls fib(1) and fib(0). So fib(1) is computed 3 times and fib(0) 2 times: repeated work that memoization removes.

What's the extra space cost of the memoization cache itself in top-down (recursive) dynamic programming, on top of the call stack?

O(n), or however many distinct subproblems there are: one cache entry per distinct input (for Fibonacci, each integer from 0 to n). This is on top of the O(n) call stack depth.

How would you decide whether a recursive solution should make one recursive call, two, or more, just from how the problem is worded?

Count how many smaller subproblems the definition refers to. One smaller instance (like 'the sum of everything after the first element') means one call. Several (like Fibonacci's 'sum of the previous two', or 'include or exclude this item') means one call per subproblem.

Why can two functions that are both 'O(n) recursive calls deep' have very different actual running times?

Depth only counts how many calls are pending at once. It says nothing about the work per call or how many sibling calls each level makes. A linear function doing O(1) per call and a tree-recursive one branching in two can both reach depth n, but the tree-recursive one does exponentially more total work.

A recursive function meant to reduce the problem size still infinitely recurses even though the recursive call is present. What's usually wrong?

The argument doesn't actually get smaller, e.g. calling recurse(n) instead of recurse(n - 1), or slicing the wrong end of an array. Each call sees the same input, so the base case is never reached.

Scenario: a recursive function correctly returns the right answer for small inputs during testing, but crashes in production. What are the two most likely explanations, in order of likelihood?

Most likely, production input is much larger or deeper than the tests, and the recursion exceeds the call stack limit even though the logic is right. Less often, an untested edge case (an empty array, a negative number, a value that skips the base case) causes infinite or far deeper recursion.

What does it mean for a recursive algorithm to have 'overlapping subproblems,' and why is that specifically what makes memoization worthwhile?

The recursion calls itself with the same arguments more than once along different paths (like fib(n-2) reached directly and via fib(n-1)). Memoization only pays off then; if every call has distinct arguments, there's nothing to reuse.

Why doesn't merge sort benefit from memoization the way naive Fibonacci does?

Each call works on a distinct, non-overlapping part of the array; mergeSort(arr[0..n/2]) and mergeSort(arr[n/2..n]) never recur with the same input. With no repeated subproblems, there's nothing to cache.

Two recursive functions each solve an n-element problem: one recurses on `n - 1` (one smaller), the other recurses on `n / 2` (halved) — both making a single recursive call. Why is one typically O(n) and the other O(log n)?

Subtracting 1 each time takes n steps to reach the base case: O(n). Halving each time takes about log₂(n) steps: O(log n). The gap grows dramatically as n grows.