Chapter 12: Recursion
Introduction
Learning Outcomes
Identify the base case and the recursive case.
Follow the call stack step by step.
Weigh recursion against loops.
Cut repeated computation with memoization.
Basics
What Is Recursion?
- A method reduces a problem to a smaller instance of itself and calls itself.
- Each call gets its own stack frame with its own parameters and local variables.
- Each call must move toward the base case; otherwise the calls never end.
Basics
Two Required Parts
The result is known directly and no new call is made (e.g. n ≤ 1 → 1).
A call that turns the problem into a smaller instance (e.g. n × f(n − 1)).
Examples
Recursive Factorial
static long factorial(int n) { if (n < 0) throw new IllegalArgumentException(); if (n <= 1) return 1; return n * factorial(n - 1); }
n! = n × (n − 1)!, 0! = 1! = 1
n ≤ 1 → 1; n drops by one on each call.
Factorial is undefined → an exception is thrown.
The Call Stack · Step through the code
Code Trace: factorial(4)
main calls factorial(4) and waits for the result.
New frame: n = 4. 4 < 0 → false, 4 <= 1 → false.
4 * factorial(3): the product needs the subresult first → this frame waits and makes a new call.
New frame: n = 3. 3 < 0 → false, 3 <= 1 → false.
3 * factorial(2): the product needs the subresult first → this frame waits and makes a new call.
New frame: n = 2. 2 < 0 → false, 2 <= 1 → false.
2 * factorial(1): the product needs the subresult first → this frame waits and makes a new call.
New frame: n = 1. 1 < 0 → false, 1 <= 1 → true: base case, return 1.
factorial(1) returned 1; its frame is gone. Now 2 × 1 = 2.
factorial(2) returned 2; its frame is gone. Now 3 × 2 = 6.
factorial(3) returned 6; its frame is gone. Now 4 × 6 = 24.
The top frame closes too; main prints 24. At most 5 frames were open → O(n) extra memory.
static long factorial(int n) { if (n < 0) throw new IllegalArgumentException(); if (n <= 1) return 1; return n * factorial(n - 1); } System.out.println(factorial(4));
The Call Stack
factorial(4): Unwinding and Returning
- Calls pile up on the stack until the base case; no multiplication has happened yet.
- Once f(1) = 1 returns, the pending products finish in reverse order: 2, 6, 24.
Examples · Step through the code
Sum from 1 to n: sum(3)
Definition: sum(n) = n + sum(n − 1), sum(0) = 0. main calls sum(3).
3 <= 0 → false.
3 + sum(2): the addition waits; new call.
2 <= 0 → false.
2 + sum(1): the addition waits; new call.
1 <= 0 → false.
1 + sum(0): the addition waits; new call.
0 <= 0 → true: base case, return 0.
sum(0) = 0 returned → 1 + 0 = 1.
sum(1) = 1 returned → 2 + 1 = 3.
sum(2) = 3 returned → 3 + 3 = 6.
6 = 3 + 2 + 1 + 0 is printed.
static int sum(int n) { if (n <= 0) return 0; return n + sum(n - 1); } System.out.println(sum(3));
Examples · Step through the code
Sum of Digits: digitSum(472)
main calls digitSum(472).
Negatives become their absolute value: m = 472 (converting to long avoids overflow at the smallest int).
A helper method does the real work.
472 < 10 → false: last digit 2, rest 47.
472 % 10 = 2 is kept; a new call with 472 / 10 = 47.
47 < 10 → false: last digit 7, rest 4.
47 % 10 = 7 is kept; a new call with 47 / 10 = 4.
4 < 10 → true: a single digit, return 4.
The subcall returned 4 → 7 + 4 = 11.
The subcall returned 11 → 2 + 11 = 13.
The helper returned 13; it is passed straight back.
4 + 7 + 2 = 13 is printed.
static int digitSum(int n) { long m = Math.abs((long) n); return digitSumPos(m); } static int digitSumPos(long n) { if (n < 10) return (int) n; return (int) (n % 10) + digitSumPos(n / 10); } System.out.println(digitSum(472));
Examples · Step through the code
Palindrome: isPal("kayak", 0, 4)
main calls isPal("kayak", 0, 4).
0 >= 4 → false.
'k' != 'k' → false: the ends match; continue inward.
Drop both ends: call isPal(s, 1, 3).
1 >= 3 → false.
'a' != 'a' → false: the ends match; continue inward.
Drop both ends: call isPal(s, 2, 2).
2 >= 2 → true: one character left in the middle → return true.
The subcall returned true; this frame returns the same value.
The subcall returned true; this frame returns the same value.
The result reaches main: true. "kayak" reads the same backward.
static boolean isPal(String s, int left, int right) { if (left >= right) return true; if (s.charAt(left) != s.charAt(right)) return false; return isPal(s, left + 1, right - 1); } System.out.println(isPal("kayak", 0, 4));
Examples · Step through the code
GCD by Euclid: gcd(48, 18)
main calls gcd(48, 18).
18 == 0 → false.
48 % 18 = 12 → call gcd(18, 12) (the numbers shrink).
12 == 0 → false.
18 % 12 = 6 → call gcd(12, 6) (the numbers shrink).
6 == 0 → false.
12 % 6 = 0 → call gcd(6, 0) (the numbers shrink).
0 == 0 → true: base case, return 6.
The subcall returned 6; it is passed straight back.
The subcall returned 6; it is passed straight back.
The subcall returned 6; it is passed straight back.
GCD(48, 18) = 6: the remainders shrank to 0; the last nonzero remainder is the GCD.
static int gcd(int a, int b) { if (b == 0) return Math.abs(a); return gcd(b, a % b); } System.out.println(gcd(48, 18));
Examples · Step through the code
Towers of Hanoi: hanoi(3, 'A', 'C', 'B')
Move 3 disks from A to C, with B as the helper. Rule: a larger disk never goes on a smaller one.
hanoi(3, A, C, B): first the top 2 disks must move A → B (to the helper).
hanoi(2, A, B, C): first the top disk must move A → C (to the helper).
Move 1: disk 1 A → C. (the hanoi(0) calls return at once)
Move 2: disk 2 A → B.
Move 3: disk 1 C → B.
Move 4: disk 3 A → C.
hanoi(2, B, C, A): first the top disk must move B → A (to the helper).
Move 5: disk 1 B → A.
Move 6: disk 2 B → C.
Move 7: disk 1 A → C.
Done: 7 = 2³ − 1 moves. n disks need 2ⁿ − 1 moves (exponential).
static void hanoi(int n, char from, char to, char via) { if (n == 0) return; hanoi(n - 1, from, via, to); System.out.print(from + "->" + to + " "); hanoi(n - 1, via, to, from); } hanoi(3, 'A', 'C', 'B');
Examples · Step through the code
Recursive Power: power(2, 4)
2⁴ = 2 × 2³, so: power(base, n) = base × power(base, n − 1), power(base, 0) = 1.
4 == 0 → false: new call for 2 × power(2, 3).
3 == 0 → false: new call for 2 × power(2, 2).
2 == 0 → false: new call for 2 × power(2, 1).
1 == 0 → false: new call for 2 × power(2, 0).
0 == 0 → true: base case, return 1.
power(2, 0) = 1 returned → 2 × 1 = 2.
power(2, 1) = 2 returned → 2 × 2 = 4.
power(2, 2) = 4 returned → 2 × 4 = 8.
power(2, 3) = 8 returned → 2 × 8 = 16.
16: n + 1 = 5 calls → O(n).
static long power(long base, int n) { if (n == 0) return 1; return base * power(base, n - 1); } System.out.println(power(2, 4));
Examples · Step through the code
Fast Power: fastPow(2, 10)
Idea: 2¹⁰ = (2⁵)², 2⁵ = (2²)² × 2. The exponent is halved on each call.
exp = 10 ≠ 0 → first fastPow(2, 5) (10 / 2 = 5).
exp = 5 ≠ 0 → first fastPow(2, 2) (5 / 2 = 2).
exp = 2 ≠ 0 → first fastPow(2, 1) (2 / 2 = 1).
exp = 1 ≠ 0 → first fastPow(2, 0) (1 / 2 = 0).
exp == 0: return 1.
half = 1; 1 is odd → 1 × 1 × 2 = 2.
half = 2; 2 is even → 2 × 2 = 4.
half = 4; 5 is odd → 4 × 4 × 2 = 32.
half = 32; 10 is even → 32 × 32 = 1024.
1024 in only 5 calls (the plain method needs 11) → O(log n).
static long fastPow(long base, int exp) { if (exp < 0) throw new IllegalArgumentException("exp < 0"); if (exp == 0) return 1; long half = fastPow(base, exp / 2); if (exp % 2 == 0) return half * half; return half * half * base; } System.out.println(fastPow(2, 10));
Examples · Step through the code
Recursive Binary Search: search(a, 38, 0, 7)
Recursion instead of a loop: each call recurses on half the range.
0 <= 7; mid = 3, a[mid] = 12.
12 < 38 → right half: search(a, 38, 4, 7).
4 <= 7; mid = 5, a[mid] = 23.
23 < 38 → right half: search(a, 38, 6, 7).
6 <= 7; mid = 6, a[mid] = 38.
38 == 38 → return 6 (base case).
The result passes back unchanged through the frames: 6.
static int search(int[] a, int x, int lo, int hi) { if (lo > hi) return -1; int mid = lo + (hi - lo) / 2; if (a[mid] == x) return mid; if (a[mid] < x) return search(a, x, mid + 1, hi); return search(a, x, lo, mid - 1); } // a = {2, 5, 8, 12, 16, 23, 38, 56} System.out.println(search(a, 38, 0, 7));
Examples
Divide and Conquer: Merge Sort
static void mergeSort(int[] a, int lo, int hi) { if (lo >= hi) return; int mid = (lo + hi) / 2; mergeSort(a, lo, mid); mergeSort(a, mid + 1, hi); int[] t = new int[hi - lo + 1]; int i = lo, j = mid + 1, k = 0; while (i <= mid && j <= hi) t[k++] = a[i] <= a[j] ? a[i++] : a[j++]; while (i <= mid) t[k++] = a[i++]; while (j <= hi) t[k++] = a[j++]; System.arraycopy(t, 0, a, lo, t.length); }
Each level merges n elements in total, and there are log₂ n levels: O(n log n) time, O(n) extra memory.
Examples · Step through the code
Reversing a String Recursively
reverse(s) = reverse(everything but the first character) + the first character.
reverse("bc") is called; 'a' waits to be appended at the end.
reverse("c") is called; 'b' waits to be appended at the end.
Length 1 ≤ 1 → base case, "c" is returned.
"c" + 'b' = "cb".
"cb" + 'a' = "cba".
cba is printed. Each call creates a new string with substring.
static String reverse(String s) { if (s.length() <= 1) return s; return reverse(s.substring(1)) + s.charAt(0); } System.out.println(reverse("abc"));
Examples · Step through the code
Code Trace: Generating Subsets
main calls subsets(a, 0, chosen) with an empty list. Each element has two choices: include / exclude.
i = 0: the array isn't finished (0 ≠ 2). First the include 1 branch.
chosen.add(1): the list is now [1].
New frame i = 1: decide on 2; include it first.
chosen.add(2): the list is [1, 2].
i = 2 = a.length: base case. Print the subset: [1, 2].
On the way back, chosen.remove(...) takes 2 out (backtracking) → [1].
The exclude 2 branch reaches a leaf: [1].
subsets(i=1) is done; remove takes 1 out → [].
The exclude 1 branch: a new frame with i = 1.
chosen.add(2): the list is [2].
Leaf: [2] is printed.
remove takes 2 out → [].
Last leaf: the empty set [].
All frames have closed. 2 elements → 2² = 4 subsets; output order: [1, 2], [1], [2], [].
static void subsets(int[] a, int i, List<Integer> chosen) { if (i == a.length) { System.out.println(chosen); return; } chosen.add(a[i]); subsets(a, i + 1, chosen); chosen.remove(chosen.size() - 1); subsets(a, i + 1, chosen); } subsets(new int[]{1, 2}, 0, new ArrayList<>());
The Call Stack
The Call Stack
- On a new call, the current method's return point and local variables are kept in its frame.
- After the base case, frames close in reverse order (last opened, first closed).
- With no base case (infinite recursion) or very deep recursion, the stack fills up and overflows:
StackOverflowError.
The Call Stack · Step through the code
Code Trace: StackOverflowError
main calls forever(0).
First frame. With no base case, forever(1) is called at once.
The second frame; the previous one is still on the stack.
The third frame. No call returns, so no frame is removed.
This goes on, but stack memory is limited (typically tens of thousands of calls).
The stack is full: the JVM throws StackOverflowError, printed to stderr.
static void forever(int n) { forever(n + 1); } forever(0);
Efficiency
Recursion or Loop?
- For self-similar problems (trees, divide and conquer), recursion stays close to the definition and reads clearly.
- For simple linear repetition, a loop runs in one frame and uses less stack memory.
- Base the choice not just on short code but on correctness, readability and resource use.
Efficiency
Comparing Factorials
| Property | Recursive | Iterative |
|---|---|---|
| Time complexity | O(n) | O(n) |
| Extra stack | O(n) | O(1) |
| Flow | Close to the definition | Explicit counter |
| Depth risk | Yes | No |
Efficiency · Step through the code
Comparison: Iterative factorial(4)
main calls factorialLoop(4).
A single frame opens; result = 1.
2 <= 4 → true
result *= 2 → 1 × 2 = 2. No new frame opened.
i++ → 3 <= 4 → true
result *= 3 → 2 × 3 = 6. No new frame opened.
i++ → 4 <= 4 → true
result *= 4 → 6 × 4 = 24. No new frame opened.
i++ → 5 <= 4 → false: the loop ends.
return 24.
24 is printed. The stack never went beyond 2 frames → O(1) extra stack.
static long factorialLoop(int n) { long result = 1; for (int i = 2; i <= n; i++) result *= i; return result; } System.out.println(factorialLoop(4));
Efficiency
The Fibonacci Problem: the fib(5) Recursion Tree
- fib(5) makes 15 calls: f(3) is computed 2 times, f(2) 3 times, f(1) 5 times (dashed orange = repeat).
- The subtrees of fib(n − 1) and fib(n − 2) overlap heavily; the number of calls grows roughly exponentially in n.
Efficiency · Step through the code
Code Trace: fib(4)
main calls fib(4).
fib(4) called: 4 <= 1 → false.
fib(3) called: 3 <= 1 → false.
fib(2) called: 2 <= 1 → false.
fib(1) called: 1 <= 1 → true, return 1.
fib(0) called: 0 <= 1 → true, return 0.
Both subresults ready: 1 + 0 = 1, return.
fib(1) called: 1 <= 1 → true, return 1.
Both subresults ready: 1 + 1 = 2, return.
fib(2) called: 2 <= 1 → false. Repeat: f(2) is computed again!
fib(1) called: 1 <= 1 → true, return 1.
fib(0) called: 0 <= 1 → true, return 0.
Both subresults ready: 1 + 0 = 1, return.
Both subresults ready: 2 + 1 = 3, return.
3 is printed. Even for a small n, 9 calls were made.
static long fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } System.out.println(fib(4));
Improvement
Memoization
- Results of solved subproblems are stored in an array (a cache).
- When the same input comes again, the recursion tree isn't rebuilt; the stored value is returned.
- 9 calls instead of 15 for fib(5); the gap grows huge for large n.
- The time savings cost O(n) extra memory.
Improvement · Step through the code
Code Trace: Memoized fib(5)
A 6-cell memo array; 0 = not computed yet.
fib(5): memo[5] == 0 → not yet known; compute it.
fib(4): memo[4] == 0 → not yet known; compute it.
fib(3): memo[3] == 0 → not yet known; compute it.
fib(2): memo[2] == 0 → not yet known; compute it.
fib(1): 1 <= 1 → true, return 1.
fib(0): 0 <= 1 → true, return 0.
memo[2] = 1 + 0 = 1 is stored and returned.
fib(1): 1 <= 1 → true, return 1.
memo[3] = 1 + 1 = 2 is stored and returned.
fib(2): memo[2] = 1 != 0 → return 1 without computing.
memo[4] = 2 + 1 = 3 is stored and returned.
fib(3): memo[3] = 2 != 0 → return 2 without computing.
memo[5] = 3 + 2 = 5 is stored and returned.
5 is printed. 9 calls in all (15 without the memo) → O(n) time.
static long fib(int n, long[] memo) { if (n <= 1) return n; if (memo[n] != 0) return memo[n]; memo[n] = fib(n - 1, memo) + fib(n - 2, memo); return memo[n]; } long[] memo = new long[6]; System.out.println(fib(5, memo));
Improvement
Tail Recursion
- The recursive call is the method's last operation; nothing is left to do on return.
- The partial result is carried in a parameter (
acc). - Some languages optimize these calls without growing the stack.
- The Java language/JVM does not guarantee tail-call optimization: frames still pile up.
static long fact(int n, long acc) { if (n <= 1) return acc; return fact(n - 1, n * acc); } // fact(4, 1) → fact(3, 4) // → fact(2, 12) → fact(1, 24) → 24
Improvement · Step through the code
Code Trace: fact(4, 1)
main calls fact(4, 1): the second parameter, acc, starts at 1.
The frame opens. 4 <= 1 → false. The last operation is the call fact(3, 4 * 1), i.e. fact(3, 4); no multiplication waits for the return.
The multiplication happened before the call: next comes fact(2, 12). The old frame has nothing left to do, yet Java does not remove it.
Next call: fact(1, 24). The stack still grows by one frame per call.
1 <= 1 → true: base case, return acc → 24. Tail recursion or not, 5 frames (main + 4) piled up: Java has no tail-call optimization.
24 passes back through the frames to main; no multiplication, just carrying the result. Memory is still O(n).
static long fact(int n, long acc) { if (n <= 1) return acc; return fact(n - 1, n * acc); } System.out.println(fact(4, 1)); // 24
Verification
Overflow and Edge Cases
factorial(20) → 2432902008176640000 (correct).factorial(21) → -4249290049419214848
No exception is thrown; the value silently wraps. A long holds at most 9223372036854775807.
power(2, -1): the base case n == 0 is never reached; n goes −1, −2, … → StackOverflowError. Guard: throw IllegalArgumentException if n < 0.
Fibonacci: recursive ≈ O(2ⁿ), iterative O(n)
| n | fib(n) recursive: number of calls | fib(n) iterative: number of passes |
|---|---|---|
| 10 | 177 | 10 |
| 20 | 21891 | 20 |
| 30 | 2692537 | 30 |
The numbers come from a counter incremented on each call; this is not a timing.
Verification
Debugging
- Show that every input reaches the base case.
- Pin down the measure by which the problem shrinks on each call.
- For a small input, tabulate the order of calls and returns (right:
sum(2)). - Assess the recursion depth and any repeated subproblems.
| Depth | Event | Value |
|---|---|---|
| 0 | sum(2) called | |
| 1 | sum(1) called | |
| 2 | sum(0) called | |
| 2 | sum(0) returned | 0 |
| 1 | sum(1) returned | 1 |
| 0 | sum(2) returned | 3 |
Summary
Chapter Summary
A base case + a recursive case that shrinks the problem.
Each call opens a frame; after the base case the frames close in reverse order.
Linear recursion uses O(n) stack; a loop usually does the same job in O(1).
Storing repeated subproblem results takes fib from exponential to O(n).
Summary
Review Questions
- What happens without a base case?
- Why does the call stack unwind in reverse order?
- How much extra stack does recursive factorial use?
- Why is naive Fibonacci slow?
- Why doesn't tail recursion make Java stack-safe?
Answers
- The calls never end; the stack fills up and a
StackOverflowErroroccurs. - Each call waits for the result of the call opened after it; the last frame opened finishes first.
- n frames → O(n).
- It recomputes the same subproblems (f(2), f(3)…) over and over; the number of calls grows exponentially.
- The JVM doesn't guarantee tail-call optimization; every call still opens a new frame.
Summary
Exercises
- Write the sum of an array recursively:
sum(a, i)= a[i] + sum(a, i + 1). - Count the digits of a number recursively (
digits(472)= 3). - Write a
toBinary(n)method that converts a decimal number to binary recursively (13 → "1101"). - How many moves does Hanoi need for n = 4? Check it with the program.
- Write the base cases for
choose(n, k) = choose(n − 1, k − 1) + choose(n − 1, k); speed it up with memoization. - Count recursively how many times a character occurs in a string.
Summary
References
- Roberts, Thinking Recursively with Java, Wiley, 2006.
- Sedgewick and Wayne, Computer Science: An Interdisciplinary Approach, Addison-Wesley, 2016: 2.3 Recursion.
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed., MIT Press, 2022.
- Liang, Introduction to Java Programming and Data Structures, 13th ed., Pearson, 2024.
- Oracle, Java SE 21 API: StackOverflowError.
- Downey and Mayfield, Think Java, 2nd ed., O'Reilly, 2019 (free online edition).