Recursion and Backtracking Questions
Recursion mechanics (base and recursive cases, tracing call stack frames, what lives on the stack versus the heap, tail calls, recursion depth limits and stack overflow diagnosis, recursion-to-iteration conversion with an explicit stack or trampoline, recursion versus iteration trade-offs) and recursion on nested data and simple divide-and-conquer (Euclid's gcd, string reversal, flattening nested lists and dictionaries lazily with generators, recursive maximum subarray). Also backtracking search over combinatorial spaces: permutations (including duplicates and the k-th permutation), subsets, combinations, combination sum, generating balanced parentheses, N-Queens (with bitmasks and symmetry), Sudoku (with minimum-remaining-values ordering), word search, palindrome partitioning, Knight's Tour and Hamiltonian paths. Covers the choose/explore/undo template, how it differs from plain DFS, state-leakage bugs, pruning, and recursion-tree complexity (O(b^d)) including call-tree counts. Memoized recursion, tree traversals, and general graph search are covered elsewhere.
Write a recursive Python function that returns all subsets (the power set) of a list of unique integers, preserving relative order within subsets: def subsets(nums: List[int]) -> List[List[int]]. Show the output for [1, 2, 3], explain the time and space complexity, and make sure results do not share mutable state.
Sample Answer
The idea in plain words
The power set of a list is the collection of all its subsets, including the empty one and the whole list. A list of n distinct items has 2^n subsets, because each item is either in a subset or out of it (two choices per item).
A backtracking way to generate them: keep a growing list path. Every path you ever hold, at any moment, is itself a subset, so record it. Then try extending it with each item that comes after the last one used (start index), recurse, and remove the item again. Moving only forward through the list is what keeps the items in their original relative order and avoids producing [2, 1] as well as [1, 2].
The brute-force alternative uses a bitmask: an integer whose binary digits each stand for one item (bit i is 1 if nums[i] is in the subset). Looping the mask from 0 to 2^n - 1 and picking items by bit also works and is just as large in output. For [1, 2, 3] the masks give:
mask 000 -> []
mask 001 -> [1]
mask 010 -> [2]
mask 011 -> [1, 2]
mask 100 -> [3]
mask 101 -> [1, 3]
mask 110 -> [2, 3]
mask 111 -> [1, 2, 3]
The recursive version extends naturally to constraints, because a branch can be abandoned the moment it breaks one.
Code
from itertools import combinations, islice
from typing import Iterator, List
def subsets(nums: List[int]) -> List[List[int]]:
result: List[List[int]] = []
path: List[int] = []
def backtrack(start: int) -> None:
result.append(path[:]) # every path is a subset; store a copy
for i in range(start, len(nums)):
path.append(nums[i]) # choose
backtrack(i + 1) # explore
path.pop() # undo
backtrack(0)
return result
print(subsets([1, 2, 3]))
def subsets_stream(nums: List[int]) -> Iterator[List[int]]:
path: List[int] = []
def backtrack(start: int) -> Iterator[List[int]]:
yield path[:]
for i in range(start, len(nums)):
path.append(nums[i])
yield from backtrack(i + 1)
path.pop()
yield from backtrack(0)
print(list(islice(subsets_stream(list(range(30))), 5)))
count = sum(1 for _ in islice(subsets_stream(list(range(20))), 2_000_000))
print("subsets of 20 items:", count)
# count the yield from layers between the generator that yields [0, 1, 2] and the caller
outer = subsets_stream([0, 1, 2, 3])
for s in outer:
if s == [0, 1, 2]:
layers, g = 0, outer
while g.gi_yieldfrom is not None:
layers, g = layers + 1, g.gi_yieldfrom
print("yield from layers above [0, 1, 2]:", layers)
break
# check against the standard library
for n in range(0, 9):
items = list(range(n))
expected = [list(c) for r in range(n + 1) for c in combinations(items, r)]
assert sorted(subsets(items)) == sorted(expected)
assert len(subsets(items)) == 2 ** n
print("checks passed")
# state leakage demo
shared = []
bad = []
bad.append(shared)
shared.append(1)
print("alias shows later change:", bad)
Output:
[[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
[[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3]]
subsets of 20 items: 1048576
yield from layers above [0, 1, 2]: 4
checks passed
alias shows later change: [[1]]
For [1, 2, 3] the output is the 8 subsets (2^3) in depth-first order: [], then everything starting with 1, then everything starting with 2, then [3].
Trace for [1, 2, 3]
This instrumented version of the same recursion prints each record, choose and undo, indented by recursion depth (depth only controls the indentation):
from typing import List
def subsets_traced(nums: List[int]) -> List[List[int]]:
result: List[List[int]] = []
path: List[int] = []
def backtrack(start: int, depth: int) -> None:
pad = " " * depth
result.append(path[:])
print(f"{pad}record {path}")
for i in range(start, len(nums)):
path.append(nums[i])
print(f"{pad}choose {nums[i]}")
backtrack(i + 1, depth + 1)
path.pop()
print(f"{pad}undo {nums[i]}")
backtrack(0, 0)
return result
subsets_traced([1, 2, 3])
Output:
record []
choose 1
record [1]
choose 2
record [1, 2]
choose 3
record [1, 2, 3]
undo 3
undo 2
choose 3
record [1, 3]
undo 3
undo 1
choose 2
record [2]
choose 3
record [2, 3]
undo 3
undo 2
choose 3
record [3]
undo 3
Each record line is one subset. Each undo brings path back to what it was before the matching choose, so the next sibling starts clean.
No shared mutable state
The line result.append(path[:]) stores a copy (path[:] makes a new list). Without it, result would contain 8 references to the one list path, which ends up empty after all the undo steps, so the output would be 8 empty lists. Aliasing means two names pointing at the same list object. The last lines of the program demonstrate it: appending shared into bad stores a reference, not a snapshot, so a later change to shared shows up inside bad. Copies also guarantee that a caller who edits one returned subset does not change another.
Complexity
- Time: the recursion makes exactly 2^n calls (one per subset), and each call copies its
path, of average length n/2. So the total is O(n * 2^n). The output itself contains n * 2^(n-1) numbers in total (for n = 3 that is 12), so no algorithm can do better than that order when it must return every subset in full. - Space: O(n) for the recursion stack and
path, plus the output, which is O(n * 2^n) elements. If you count the output as space, the output dominates.
Handling n up to 30: stream, do not materialize
With n = 30 there are 2^30 = 1,073,741,824 subsets, far too many to hold in one list. The subsets_stream generator (a function that yields one value at a time and pauses until the caller asks for the next) produces each subset on demand, so memory stays O(n) no matter how many are consumed. islice(g, k) takes just the first k values from a generator and stops. The program takes the first 5 for 30 items, and counts all 1,048,576 subsets of 20 items without ever storing them. Time is still exponential if you consume everything; streaming fixes memory, not running time. yield from backtrack(i + 1) means "pass along every value the inner generator produces". The subset [0, 1, 2] is produced by the fourth nested backtrack call (the one with start = 3), so it is handed up through four yield from layers (the three backtrack calls above it and the outer subsets_stream) before the caller sees it; the program counts them and prints 4. A subset with d items crosses d + 1 layers, and d is at most n, so every subset costs O(n) to deliver plus the copy.
Edge cases and common mistakes
- Empty list: returns
[[]](one subset, the empty one), not[]. - A single item returns
[[], [x]]. - The input is assumed to hold unique integers; with duplicates you would get repeated subsets unless you sort and skip equal neighbours at the same depth.
- Recording
pathwithout copying (aliasing), or recording only at the leaves: here every node records, which is what captures subsets of every length. - Recursion depth is at most n, so there is no recursion-limit concern at n = 30.
Running the code
python3.12 power_set.py
Save the first program above as power_set.py and the traced version as its own file. No packages are needed (the itertools import is from the standard library, used for the check and for islice).
Here is a naive recursive Fibonacci: fib(n) = n if n < 2 else fib(n-1) + fib(n-2). Draw the call tree for n = 6, count the function calls, state the asymptotic time and space, and explain what changes in the number of calls when results are cached.
Sample Answer
The idea in plain words
Naive recursive Fibonacci recomputes the same subproblems over and over. fib(6) asks for fib(5) and fib(4), but fib(5) also asks for fib(4), so the work for fib(4) is done twice, and the repetition compounds down the tree. Caching (remembering each answer the first time it is computed, also called memoization) removes the repeats, so each value is computed once.
The call tree for n = 6 and the call count
The program prints one line per call, indented by depth in the tree, and counts the calls.
calls = 0
def fib(n, depth=0):
global calls
calls += 1
print(" " * depth + f"fib({n})")
if n < 2:
return n
return fib(n - 1, depth + 1) + fib(n - 2, depth + 1)
print("value:", fib(6))
print("naive calls:", calls)
memo_calls = 0
def fib_cached(n, cache, depth=0):
global memo_calls
memo_calls += 1
if n < 2:
note = "base case"
elif n in cache:
note = "cache hit"
else:
note = "computed"
print(" " * depth + f"fib({n}) {note}")
if n < 2:
return n
if n not in cache:
cache[n] = fib_cached(n - 1, cache, depth + 1) + fib_cached(n - 2, cache, depth + 1)
return cache[n]
print("cached value:", fib_cached(6, {}))
print("cached calls:", memo_calls)
# call counts for growing n (naive), counted not timed
def count_calls(n):
return 1 if n < 2 else 1 + count_calls(n - 1) + count_calls(n - 2)
def fib_loop(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
for n in (10, 20, 30):
print(n, count_calls(n), 2 * fib_loop(n + 1) - 1)
for n in (10, 20, 30):
print(n, round(fib_loop(n + 1) / fib_loop(n), 4))
def cached_call_count(n):
seen, count = {}, 0
def go(m):
nonlocal count
count += 1
if m < 2:
return m
if m not in seen:
seen[m] = go(m - 1) + go(m - 2)
return seen[m]
go(n)
return count
for n in (0, 1, 2, 6, 30):
print("cached calls for n =", n, ":", cached_call_count(n))
Output:
fib(6)
fib(5)
fib(4)
fib(3)
fib(2)
fib(1)
fib(0)
fib(1)
fib(2)
fib(1)
fib(0)
fib(3)
fib(2)
fib(1)
fib(0)
fib(1)
fib(4)
fib(3)
fib(2)
fib(1)
fib(0)
fib(1)
fib(2)
fib(1)
fib(0)
value: 8
naive calls: 25
fib(6) computed
fib(5) computed
fib(4) computed
fib(3) computed
fib(2) computed
fib(1) base case
fib(0) base case
fib(1) base case
fib(2) cache hit
fib(3) cache hit
fib(4) cache hit
cached value: 8
cached calls: 11
10 177 177
20 21891 21891
30 2692537 2692537
10 1.6182
20 1.618
30 1.618
cached calls for n = 0 : 1
cached calls for n = 1 : 1
cached calls for n = 2 : 3
cached calls for n = 6 : 11
cached calls for n = 30 : 59
The tree has 25 calls for n = 6. Counting the lines per argument: fib(6) 1, fib(5) 1, fib(4) 2, fib(3) 3, fib(2) 5, fib(1) 8, fib(0) 5, which sums to 25. Only 7 distinct values (0 through 6) are ever needed, yet fib(2) is computed 5 times and fib(3) 3 times.
The call count follows its own recurrence: calls(n) = 1 + calls(n-1) + calls(n-2) (one call for this node, plus all the calls made under each child), with calls(0) = calls(1) = 1. It solves to 2 * fib(n+1) - 1, and the reason is short. Add 1 to both sides: calls(n) + 1 = (calls(n-1) + 1) + (calls(n-2) + 1). So the sequence calls(n) + 1 obeys exactly the Fibonacci rule (each term is the sum of the previous two). Its first two terms are calls(0) + 1 = 2 and calls(1) + 1 = 2, which are 2 * fib(1) and 2 * fib(2). A sequence with the Fibonacci rule that starts at twice the Fibonacci start stays twice Fibonacci forever, so calls(n) + 1 = 2 * fib(n+1). Check for n = 6: fib(7) = 13, so 2 * 13 - 1 = 25. The first for n in (10, 20, 30) loop in the program prints the counted value next to the formula (10 177 177, 20 21891 21891, 30 2692537 2692537), and they agree (for n = 30, 2,692,537 calls, with fib(31) = 1,346,269).
Asymptotic time and space (naive version)
- Time: the call count grows like
fib(n)itself. The ratio of consecutive Fibonacci numbers settles at about 1.618 (the secondfor n in (10, 20, 30)loop printsfib(n+1) / fib(n)as 1.6182, 1.618 and 1.618 for n = 10, 20 and 30). That number is the golden ratio, written phi, equal to(1 + sqrt(5)) / 2. So the calls grow likephi^n: every extra step of n multiplies the work by about 1.618. Growth like that is exponential (n sits in the exponent). Compare polynomial growth such as n^2 or n^3, where n is the base: doubling n multiplies n^2 work by 4, but adding just 10 to n here multiplies the work by about 123 (1.618^10). The time is O(phi^n). It is usually quoted as O(2^n), which is a looser upper bound: still true, because 1.618^n never exceeds 2^n, but not as tight as it could be. Going from n = 20 to n = 30 multiplied the calls from 21,891 to 2,692,537, about 123 times. - Space: O(n). Time is spent on the whole tree, but the stack only holds one root-to-current path at a time, and the longest path (always taking
n-1) has n frames: for n = 6 that isfib(6), fib(5), fib(4), fib(3), fib(2), fib(1).
What changes with a cache
With the cache in fib_cached, fib(6) made 11 calls instead of 25. The cached tree printed above shows where each call goes. fib(6) down to fib(2) are marked computed: the five real computations (n = 2 through 6), each done once. Every computed node makes two calls. The 11 calls break down as 5 computed, 3 base cases (fib(1) and fib(0) under fib(2), and fib(1) under fib(3)) and 3 cache hit calls: the second call of fib(4) is fib(2), the second call of fib(5) is fib(3), and the second call of fib(6) is fib(4). Each hit returns the stored value at once, without recursing, which is what cuts the tree down. For n >= 1 the cached version makes 2n - 1 calls (n = 6 gives 11, n = 1 gives 1): there are n - 1 computed nodes (n = 2 through n), each makes two calls, and every call except the first is one of those, so the total is 2(n-1) + 1. The last lines of the output count it for n = 0, 1, 2, 6 and 30 (1, 1, 3, 11, 59). The formula does not apply at n = 0, where the single call is a base case and there are no computed nodes, so the count is 1, not -1. Time drops from exponential to O(n). Space stays O(n): the recursion depth is still n, and for n >= 1 the cache holds n - 1 entries.
| Calls for n = 6 | Time | Space | |
|---|---|---|---|
| Naive | 25 | O(phi^n), exponential | O(n) stack |
| Cached | 11 | O(n) | O(n) stack + O(n) cache |
This is the bridge to dynamic programming: the subproblems overlap, so storing them turns a tree of repeated work into a straight line.
Edge cases and common mistakes
fib(0)andfib(1)are the base cases (one call each). Forgetting that both are needed, or writingn == 1only, makesfib(0)recurse into negative numbers.- A mutable default cache (
def fib(n, cache={})) is shared between calls in Python; here the cache is passed in so every top-level call starts clean. - For n near 1000 or more, the cached recursive version needs more than Python's default limit of 1000 frames and raises
RecursionError; a loop avoids it.
Running the code
python3.12 fib_calls.py
Save the program above as fib_calls.py. No packages are needed. The output is deterministic.
Implement a recursive reverseString(s) in Java without loops or library reverse helpers. Explain your base and recursive case, handle null and empty input, and list the edge cases you would unit test.
Sample Answer
The idea
Reversing a string recursively means expressing the answer for a string in terms of the answer for a smaller one. Two framings work. Reverse(s) is "reverse of everything after the first character, followed by the first character". Or: swap the first and last characters, then reverse what is between them. Both need a base case, the smallest input that needs no work: an empty string and a one-character string are their own reverse. Each call must move toward the base case by shrinking its argument (one character removed, or two for the swap form), otherwise the recursion never reaches the base case and eventually ends in a StackOverflowError.
Approach
- Decide the contract for
null: herenullreturnsnull(the alternative, throwingIllegalArgumentException, is equally defensible; what matters is that it is documented and tested). - Base case: length 0 or 1 returns the input.
- Recursive case:
reverseString(s.substring(1)) + s.charAt(0). - The second form works on a
char[]with two indexes that move toward each other, so no substrings are created.
The code
public class Reverser {
// Simple version: reverse(s) = reverse(everything after the first char) + first char.
static String reverseString(String s) {
if (s == null) {
return null; // contract: null in, null out
}
if (s.length() <= 1) { // base case: "" and one char are their own reverse
return s;
}
return reverseString(s.substring(1)) + s.charAt(0);
}
// Index version: swap the two ends in a char[] and recurse on the middle. No string copies per call.
static String reverseStringSwap(String s) {
if (s == null) {
return null;
}
char[] chars = s.toCharArray();
swapEnds(chars, 0, chars.length - 1);
return new String(chars);
}
private static void swapEnds(char[] chars, int left, int right) {
if (left >= right) { // base case: pointers met or crossed
return;
}
char tmp = chars[left];
chars[left] = chars[right];
chars[right] = tmp;
swapEnds(chars, left + 1, right - 1);
}
static void check(String input, String expected) {
String a = reverseString(input);
String b = reverseStringSwap(input);
boolean ok = java.util.Objects.equals(a, expected) && java.util.Objects.equals(b, expected);
System.out.println((ok ? "PASS " : "FAIL ") + "input=" + (input == null ? "null" : "\"" + input + "\"")
+ " -> " + (a == null ? "null" : "\"" + a + "\""));
}
public static void main(String[] args) {
check(null, null);
check("", "");
check("a", "a");
check("ab", "ba");
check("hello", "olleh");
check("racecar", "racecar");
check("a b", "b a");
// depth: each call adds a stack frame
for (int n : new int[] {1_000, 5_000, 50_000}) {
String big = "x".repeat(n);
try {
reverseString(big);
System.out.println("n=" + n + " reverseString ok");
} catch (StackOverflowError e) {
System.out.println("n=" + n + " reverseString StackOverflowError");
}
try {
reverseStringSwap(big);
System.out.println("n=" + n + " reverseStringSwap ok");
} catch (StackOverflowError e) {
System.out.println("n=" + n + " reverseStringSwap StackOverflowError");
}
}
}
}
Output:
PASS input=null -> null
PASS input="" -> ""
PASS input="a" -> "a"
PASS input="ab" -> "ba"
PASS input="hello" -> "olleh"
PASS input="racecar" -> "racecar"
PASS input="a b" -> "b a"
n=1000 reverseString ok
n=1000 reverseStringSwap ok
n=5000 reverseString ok
n=5000 reverseStringSwap ok
n=50000 reverseString StackOverflowError
n=50000 reverseStringSwap ok
The first seven lines are the unit-test style checks, each run against both versions. The remaining lines show how deep each version can go on this JVM with its default stack settings: 5,000 characters is fine for both, while 50,000 characters overflows the stack for reverseString and still succeeds for reverseStringSwap. The exact threshold depends on the JVM and its thread stack size (-Xss is the JVM option that sets it), so treat the numbers as an illustration of the trend, not a fixed limit.
Trace for "abc" (simple version)
public class ReverseTrace {
static String reverseString(String s, int depth) {
String pad = " ".repeat(depth);
System.out.println(pad + "call reverseString(\"" + s + "\")");
if (s.length() <= 1) {
System.out.println(pad + "base case, return \"" + s + "\"");
return s;
}
String inner = reverseString(s.substring(1), depth + 1);
String result = inner + s.charAt(0);
System.out.println(pad + "\"" + inner + "\" + '" + s.charAt(0) + "' -> return \"" + result + "\"");
return result;
}
public static void main(String[] args) {
System.out.println(reverseString("abc", 0));
// space for the simple version: the pending frames hold substrings of length n-1, n-2, ..., 1
for (int n : new int[] {5, 1000}) {
long chars = 0;
for (int len = n - 1; len >= 1; len--) {
chars += len;
}
System.out.println("n=" + n + ": pending substrings hold " + chars + " characters in total");
}
// an emoji is one code point but two 16-bit chars (a surrogate pair)
String s = "a😀b";
String expected = "b😀a";
System.out.println("length() = " + s.length() + ", codePointCount = " + s.codePointCount(0, s.length()));
StringBuilder units = new StringBuilder();
for (char ch : s.toCharArray()) {
units.append(String.format("%04X ", (int) ch));
}
System.out.println("chars of \"a<emoji>b\" in hex: " + units.toString().trim());
StringBuilder swapped = new StringBuilder();
for (char ch : Reverser.reverseString(s).toCharArray()) {
swapped.append(String.format("%04X ", (int) ch));
}
System.out.println("chars after unit-by-unit reverse: " + swapped.toString().trim());
System.out.println("pair kept by simple version: " + Reverser.reverseString(s).equals(expected));
System.out.println("pair kept by swap version: " + Reverser.reverseStringSwap(s).equals(expected));
System.out.println("pair kept by StringBuilder: " + new StringBuilder(s).reverse().toString().equals(expected));
}
}
Output:
call reverseString("abc")
call reverseString("bc")
call reverseString("c")
base case, return "c"
"c" + 'b' -> return "cb"
"cb" + 'a' -> return "cba"
cba
n=5: pending substrings hold 10 characters in total
n=1000: pending substrings hold 499500 characters in total
length() = 4, codePointCount = 3
chars of "a<emoji>b" in hex: 0061 D83D DE00 0062
chars after unit-by-unit reverse: 0062 DE00 D83D 0061
pair kept by simple version: false
pair kept by swap version: false
pair kept by StringBuilder: true
The first seven lines are the walk-through for "abc": each call waits for the inner result and appends its own first character on the way back: "c", then "cb", then "cba". The next two lines add up the lengths of the substrings that are alive at once (4 + 3 + 2 + 1 = 10 characters for n = 5, and 499,500 for n = 1,000), which is the O(n^2) space count in the next section. The remaining lines are the emoji check from the edge cases: Java strings store text as 16-bit char units, so a character outside the basic 16-bit range, such as an emoji, takes two units called a surrogate pair. The string a<emoji>b has length() 4 but only 3 code points (a code point is one real character). The hex lines show the units D83D DE00 (the pair) sitting between 0061 and 0062; reversing unit by unit puts DE00 before D83D, which is no longer a valid pair, so the simple and swap versions fail the check while StringBuilder.reverse(), which treats a pair as one character, passes.
Complexity
reverseString: n calls for a string of n >= 1 characters (the last one is the base case), but each call copies the remaining string twice (substring, then the+concatenation), so time is O(n^2). Space is O(n^2) characters at peak, because each of the n pending frames holds its own, shorter substring (lengths n-1, n-2, ... 1, which add up to n(n-1)/2: 10 characters for n = 5 and 499,500 for n = 1,000, as the trace output shows), plus O(n) frames. A stack frame is the block of memory the JVM sets aside for one active method call.reverseStringSwap: floor(n/2) + 1 calls (floor means rounding down; the last call is the base case that finds the pointers met or crossed), so 3 calls for n = 5, 2 for n = 2 and 1 for n = 1. Each call is O(1), so O(n) time; thechar[]is O(n) and the stack depth is floor(n/2) + 1, so O(n) space.- Either way the recursion depth is linear in the input, which is why recursion is a poor way to reverse long strings in Java; a loop or
StringBuilder.reverse()uses constant stack. A tail call is a call that is the very last action of a method, so its frame could be reused. Java does not do that, and the simple version is not a tail call anyway because the concatenation happens after the call returns. Running out of stack space throwsStackOverflowError.
Edge cases to unit test
null(returnsnull),"", one character.- Even and odd lengths ("ab", "abc"): the swap version stops when the indexes meet or cross, so the odd middle character stays put.
- Palindromes ("racecar") and strings with spaces or repeated characters.
- Very long input (the depth test above) to confirm the failure mode is understood.
- Characters outside the basic range: Java strings are sequences of 16-bit units, so an emoji is two units (a surrogate pair). Reversing unit by unit swaps the two halves of the pair (see the hex lines in the trace output), so the result is not "b" + emoji + "a" in either version here, whereas
new StringBuilder(s).reverse()keeps the pair intact (the last three lines of the trace output).
Common mistakes
- No base case for the empty string:
"".substring(1)throws aStringIndexOutOfBoundsException(it is evaluated beforecharAt(0)inreverseString(s.substring(1)) + s.charAt(0), so it is the call that fails first). - A base case of length 1 only (
s.length() == 1): an empty input is never matched, and it fails at once with the sameStringIndexOutOfBoundsExceptionfromsubstring(1). With no base case at all the recursion walks down to the empty string and fails there, rather than running forever. - Recursing with the same argument, or an off-by-one in
substring. - Appending the first character before the recursive result, which returns the string unchanged.
Follow-ups
- Make it iterative (a loop over a
char[]with two indexes) and state the space. - Reverse the words of a sentence, not the characters.
- Handle surrogate pairs correctly by working with code points (whole characters) instead of 16-bit units, for example with
String.codePoints().
Running the code
Java 21 (eclipse-temurin:21-jdk).
Save the listings as Reverser.java and ReverseTrace.java in one folder.
javac Reverser.java ReverseTrace.java
java Reverser
java ReverseTrace
Trace factorial(4) by hand. Write out the call and return sequence step by step, showing each stack frame, its local values, and the value returned to the caller.
Sample Answer
The idea in plain words
factorial(n) is defined as n * factorial(n-1), with factorial(1) = 1 as the stopping point (the base case). Tracing it by hand means following the call stack: the pile of unfinished function calls, where each call owns a frame holding its own copy of n and a spot to resume in its caller. A call pushes a frame; a return pops it. Calls go down until the base case, then values come back up.
The trace in two phases
Phase 1, going down (nothing is multiplied yet):
factorial(4)starts withn=4. It cannot answer until it knowsfactorial(3), so it pauses and calls it.factorial(3)starts withn=3and pauses to callfactorial(2).factorial(2)starts withn=2and pauses to callfactorial(1).factorial(1)starts withn=1. This is the base case, so it needs no further call.
At this moment four frames are on the stack, with n=4 at the bottom and n=1 on top.
Phase 2, coming back up (the multiplications happen here):
factorial(1)returns1and its frame is popped.factorial(2)resumes withn=2and the returned1, computes2 * 1 = 2, returns2.factorial(3)resumes withn=3and the returned2, computes3 * 2 = 6, returns6.factorial(4)resumes withn=4and the returned6, computes4 * 6 = 24, returns24.
Code that prints the stack
The program keeps its own list of the live frames' n values so each event can print the stack from bottom to top. A snapshot printed on a return line is taken just before that frame is popped.
stack = []
def show(event):
frames = " | ".join(f"fact(n={n})" for n in stack) or "(empty)"
print(f"{event:<28} stack bottom->top: {frames}")
def fact(n):
stack.append(n)
show(f"call fact({n})")
if n == 1:
value = 1
show(f"fact(1) returns {value}")
else:
sub = fact(n - 1)
value = n * sub
show(f"fact({n}) = {n}*{sub} returns {value}")
stack.pop()
return value
print("answer:", fact(4))
Output:
call fact(4) stack bottom->top: fact(n=4)
call fact(3) stack bottom->top: fact(n=4) | fact(n=3)
call fact(2) stack bottom->top: fact(n=4) | fact(n=3) | fact(n=2)
call fact(1) stack bottom->top: fact(n=4) | fact(n=3) | fact(n=2) | fact(n=1)
fact(1) returns 1 stack bottom->top: fact(n=4) | fact(n=3) | fact(n=2) | fact(n=1)
fact(2) = 2*1 returns 2 stack bottom->top: fact(n=4) | fact(n=3) | fact(n=2)
fact(3) = 3*2 returns 6 stack bottom->top: fact(n=4) | fact(n=3)
fact(4) = 4*6 returns 24 stack bottom->top: fact(n=4)
answer: 24
The table to write on a whiteboard
| Step | Event | n in that frame | Frames on the stack after the event | Value handed back |
|---|---|---|---|---|
| 1 | call fact(4) | 4 | 1 | none yet |
| 2 | call fact(3) | 3 | 2 | none yet |
| 3 | call fact(2) | 2 | 3 | none yet |
| 4 | call fact(1), base case | 1 | 4 (the deepest point) | none yet |
| 5 | fact(1) returns | 1 | 3 after the pop | 1 |
| 6 | fact(2) returns 2 * 1 | 2 | 2 after the pop | 2 |
| 7 | fact(3) returns 3 * 2 | 3 | 1 after the pop | 6 |
| 8 | fact(4) returns 4 * 6 | 4 | 0 after the pop | 24 |
Four calls and four returns: the stack grows to 4 frames and then shrinks back to 0.
Complexity
For factorial(n): n calls, each doing one multiplication, so O(n) multiplications; counting each as one step gives O(n) time. The deepest point holds n frames at once, so O(n) space on the call stack. (The numbers themselves also grow: Python integers have arbitrary precision, so there is no overflow (the largest products cost more than one step each, which the step count ignores), but in a fixed-width language such as Java int, factorial(13) already overflows 32 bits.)
Edge cases and common mistakes
factorial(0): with the base case written asn == 1, this would recurse to-1, -2, ...and only stop when Python hits its recursion limit (1000 frames by default) and raisesRecursionError. Writing the base case asn <= 1handles 0 and 1 and also stops a negative input from looping; a production version should reject negativenexplicitly.- Multiplying on the way down instead of on the way up: nothing is multiplied until the base case has returned, so the first multiplication happens in the frame for
n=2. - Treating
nas one shared variable: each frame has its ownn, which is whyfact(4)still hasn=4afterfact(3)finishes.
Running the code
python3.12 factorial_stack.py
Save the program above as factorial_stack.py. No packages are needed.
Write factorial(n) twice in Python, once recursively and once iteratively. Compare time and space for both, and explain whether tail-call optimization would change the recursive version's space and why Python does not do it.
Sample Answer
The idea
The factorial of n (written n!) is the product 1 x 2 x ... x n, with 0! = 1. It can be defined by itself: n! = n x (n-1)!, with 1 (or 0) as the stopping point. That definition is the recursive version. A loop multiplying 2, 3, ..., n into a running product is the iterative version. Both compute the same number with the same n - 1 multiplications; what differs is how much stack they use. The call stack is the fixed-size region of memory that holds one stack frame (a block with that call's arguments, local variables and return point) for every call that has started but not finished. The recursive version keeps one frame alive per pending multiplication; the loop keeps none.
A third form carries the running product in a parameter called an accumulator: factorial_tail(n, acc) multiplies as it goes down, so nothing is left to do when the inner call returns. The listing below includes it.
The code
import math
import sys
def factorial_recursive(n: int) -> int:
if n < 0:
raise ValueError("factorial is undefined for negative numbers")
if n <= 1: # base case: 0! = 1! = 1
return 1
return n * factorial_recursive(n - 1)
def factorial_iterative(n: int) -> int:
if n < 0:
raise ValueError("factorial is undefined for negative numbers")
result = 1
for k in range(2, n + 1):
result *= k
return result
def factorial_tail(n: int, acc: int = 1) -> int:
"""Tail-recursive form: the recursive call is the last thing done, and the product rides in acc."""
if n < 0:
raise ValueError("factorial is undefined for negative numbers")
if n <= 1:
return acc
return factorial_tail(n - 1, acc * n)
for n in (0, 1, 5, 20):
assert factorial_recursive(n) == factorial_iterative(n) == factorial_tail(n) == math.factorial(n)
print(factorial_recursive(5), factorial_iterative(5), factorial_tail(5), factorial_recursive(20))
print("recursion limit:", sys.getrecursionlimit())
for fn in (factorial_recursive, factorial_tail, factorial_iterative):
for n in (900, 1500):
try:
fn(n)
print(f"{fn.__name__}({n}): ok")
except RecursionError:
print(f"{fn.__name__}({n}): RecursionError")
Output:
120 120 120 2432902008176640000
recursion limit: 1000
factorial_recursive(900): ok
factorial_recursive(1500): RecursionError
factorial_tail(900): ok
factorial_tail(1500): RecursionError
factorial_iterative(900): ok
factorial_iterative(1500): ok
factorial_tail is the tail-recursive form: it carries the running product in acc, so the recursive call is the very last thing the function does. factorial_recursive is not tail-recursive, because after the inner call returns it still has to multiply by n.
Time and space
max_depth = 0
def factorial_counted(n, depth=1):
global max_depth
max_depth = max(max_depth, depth)
if n <= 1:
return 1
return n * factorial_counted(n - 1, depth + 1)
for n in (5, 50, 500):
max_depth = 0
value = factorial_counted(n)
print(f"n={n}: deepest frame count={max_depth}, result has {value.bit_length()} bits")
Output:
n=5: deepest frame count=5, result has 7 bits
n=50: deepest frame count=50, result has 215 bits
n=500: deepest frame count=500, result has 3768 bits
The output shows the call depth equals n (the frames alive at the deepest point) and how big the result gets: a 500! needs 3,768 bits. bit_length() returns how many binary digits a number needs.
| Recursive | Iterative | |
|---|---|---|
| Multiplications | n - 1 | n - 1 |
| Time | O(n) multiplications | O(n) multiplications |
| Extra stack | O(n) frames | O(1) |
| Result size | O(n log n) bits | O(n log n) bits |
The result size in the table has a short reason: n! is at most n^n (n factors, each at most n), and a number of at most n^n needs at most floor(n log2 n) + 1 bits (the + 1 only matters for tiny n: 1! = 1 needs one bit while n log2 n is 0). The bound is loose: by Stirling's approximation n! has about n log2 n - 1.44 n bits (plus a small logarithmic term), so the bound overshoots by an amount that grows in proportion to n, and the ratio of actual bits to n log2 n climbs toward 1 as n grows (0.60, 0.76 and 0.84 for the three values of n in the listing below, which prints both quantities):
import math
for n in (5, 50, 500):
bits = math.factorial(n).bit_length()
print(f"n={n}: {n}! has {bits} bits; n * log2(n) = {n * math.log2(n):.0f}")
Output:
n=5: 5! has 7 bits; n * log2(n) = 12
n=50: 50! has 215 bits; n * log2(n) = 282
n=500: 500! has 3768 bits; n * log2(n) = 4483
Python integers are arbitrary precision (they grow as large as memory allows instead of overflowing at 64 bits), so a multiplication is not constant time once the product is large: each step multiplies a big number by a small one, which costs time proportional to the number's length. Counting multiplications, which is the usual interview answer, both versions are O(n), and both must hold the same result of O(n log n) bits. The recursive version also holds n stack frames at once, and CPython allows 1000 by default, which is why factorial_recursive(1500) raises RecursionError while factorial_iterative(1500) returns.
Would tail-call optimization change the space?
Tail-call optimization (TCO) means that when a function's last action is a call, the runtime reuses the current stack frame instead of adding another, so the recursion runs in constant stack space. For factorial_tail that would change the space from O(n) to O(1); for factorial_recursive it would not, because the multiplication happens after the call returns, so the frame cannot be dropped. To benefit, you must first rewrite to the accumulator form, as factorial_tail does.
Why Python does not do it
CPython never reuses the frame for a tail call: factorial_tail(1500) raises RecursionError in the output just like the plain version. Python's creator explained the decision in a 2009 blog post: eliminating tail calls removes frames from tracebacks (the list of active calls Python prints when an error is raised), which makes debugging harder; he also objected that code written to rely on it would break on implementations without it, and that rebinding names at run time makes it impossible to know at compile time that a call is a self-call. His recommended alternative is to write the loop. Raising the limit with sys.setrecursionlimit only moves the wall, and a very high limit can crash the interpreter, so a loop (or math.factorial) is the real answer for large n. Scheme (a Lisp-family language) requires TCO by specification; compilers for C-family languages may do it as an optimisation but are not required to.
Edge cases and common mistakes
- n = 0 and n = 1 both return 1; a base case of only
n == 0works but makes one more call. - Negative input has no factorial. The code raises
ValueError, because then <= 1base case would otherwise quietly return 1. - A base case of
n == 1alone, without the negative-input check, makesfactorial(0)recurse through -1, -2, ... untilRecursionError; with the check in the listing it raisesValueErrorat -1 instead. - Believing the accumulator form is automatically O(1) in Python: it is not.
- Floats:
factorial_recursive(5.0)andfactorial_tail(5.0)return120.0by accident, whilefactorial_iterative(5.0)raisesTypeErrorbecauserangeneeds integers. Reject non-integers up front so all versions behave the same.
Follow-ups
- Compute n! mod m for huge n: reduce after each multiplication so numbers stay small.
- Memoise factorials for many queries: one table of prefix products answers each query in O(1).
- Recursion to iteration in general: the explicit stack, or the trampoline pattern (a loop that repeatedly calls a function that returns the next function to call, instead of letting each call nest).
Running the code
Python 3.12, standard library only.
python3 factorial.py ; python3 factorial_depth.py ; python3 factorial_bits.py (the three listings)
Unlock Full Question Bank
Get access to all 15 Recursion and Backtracking interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.