Chapter 12: Recursion

Computer Fundamentals and Introduction to Programming
Base caseCallsStackEfficiencyMemoization
Sercan KÜLCÜ · Giresun University

Introduction

Learning Outcomes

Structure

Identify the base case and the recursive case.

Tracing

Follow the call stack step by step.

Comparison

Weigh recursion against loops.

Improvement

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.
factorial(4) = 4 × factorial(3)factorial(3) = 3 × factorial(2)factorial(2) = 2 × factorial(1)factorial(1) = 1base case

Basics

Two Required Parts

Base case

The result is known directly and no new call is made (e.g. n ≤ 1 → 1).

Recursive case

A call that turns the problem into a smaller instance (e.g. n × f(n − 1)).

call f(n)base casereached?yesreturn the result directlynoshrink and call f(n − 1)new call

Examples

Recursive Factorial

static long factorial(int n) {
    if (n < 0)
        throw new IllegalArgumentException();
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}
Definition

n! = n × (n − 1)!, 0! = 1! = 1

Base case

n ≤ 1 → 1; n drops by one on each call.

Negative n

Factorial is undefined → an exception is thrown.

-2-1012345error (n < 0)base: 1recursive: n × f(n − 1)n drops by one each call → reaches the base

The Call Stack · Step through the code

Code Trace: factorial(4)

main()main (stack bottom) → stack grows this way → top

main calls factorial(4) and waits for the result.

main()factorial(4)n=4main (stack bottom) → stack grows this way → top

New frame: n = 4. 4 < 0 → false, 4 <= 1 → false.

main()factorial(4)n=4: 4 × ?main (stack bottom) → stack grows this way → top

4 * factorial(3): the product needs the subresult first → this frame waits and makes a new call.

main()factorial(4)n=4: 4 × ?factorial(3)n=3main (stack bottom) → stack grows this way → top

New frame: n = 3. 3 < 0 → false, 3 <= 1 → false.

main()factorial(4)n=4: 4 × ?factorial(3)n=3: 3 × ?main (stack bottom) → stack grows this way → top

3 * factorial(2): the product needs the subresult first → this frame waits and makes a new call.

main()factorial(4)n=4: 4 × ?factorial(3)n=3: 3 × ?factorial(2)n=2main (stack bottom) → stack grows this way → top

New frame: n = 2. 2 < 0 → false, 2 <= 1 → false.

main()factorial(4)n=4: 4 × ?factorial(3)n=3: 3 × ?factorial(2)n=2: 2 × ?main (stack bottom) → stack grows this way → top

2 * factorial(1): the product needs the subresult first → this frame waits and makes a new call.

main()factorial(4)n=4: 4 × ?factorial(3)n=3: 3 × ?factorial(2)n=2: 2 × ?factorial(1)n=1main (stack bottom) → stack grows this way → top

New frame: n = 1. 1 < 0 → false, 1 <= 1 → true: base case, return 1.

main()factorial(4)n=4: 4 × ?factorial(3)n=3: 3 × ?factorial(2)n=2: 2 × ?factorial(1)↩ return 1main (stack bottom) → stack grows this way → top

factorial(1) returned 1; its frame is gone. Now 2 × 1 = 2.

main()factorial(4)n=4: 4 × ?factorial(3)n=3: 3 × ?factorial(2)↩ return 2main (stack bottom) → stack grows this way → top

factorial(2) returned 2; its frame is gone. Now 3 × 2 = 6.

main()factorial(4)n=4: 4 × ?factorial(3)↩ return 6main (stack bottom) → stack grows this way → top

factorial(3) returned 6; its frame is gone. Now 4 × 6 = 24.

main()factorial(4)↩ return 24main (stack bottom) → stack grows this way → top

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

f(4) = 4 × f(3)f(3) = 3 × f(2)f(2) = 2 × f(1)f(1) = 1f(1) = 1f(2) = 2f(3) = 6f(4) = 24calls open (stack grows) ↓↑ returns (stack shrinks)
  • 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)

main()main (stack bottom) → stack grows this way → top

Definition: sum(n) = n + sum(n − 1), sum(0) = 0. main calls sum(3).

main()sum(3)n=3main (stack bottom) → stack grows this way → top

3 <= 0 → false.

main()sum(3)n=3: 3 + ?main (stack bottom) → stack grows this way → top

3 + sum(2): the addition waits; new call.

main()sum(3)n=3: 3 + ?sum(2)n=2main (stack bottom) → stack grows this way → top

2 <= 0 → false.

main()sum(3)n=3: 3 + ?sum(2)n=2: 2 + ?main (stack bottom) → stack grows this way → top

2 + sum(1): the addition waits; new call.

main()sum(3)n=3: 3 + ?sum(2)n=2: 2 + ?sum(1)n=1main (stack bottom) → stack grows this way → top

1 <= 0 → false.

main()sum(3)n=3: 3 + ?sum(2)n=2: 2 + ?sum(1)n=1: 1 + ?main (stack bottom) → stack grows this way → top

1 + sum(0): the addition waits; new call.

main()sum(3)n=3: 3 + ?sum(2)n=2: 2 + ?sum(1)n=1: 1 + ?sum(0)n=0main (stack bottom) → stack grows this way → top

0 <= 0 → true: base case, return 0.

main()sum(3)n=3: 3 + ?sum(2)n=2: 2 + ?sum(1)n=1: 1 + ?sum(0)↩ return 0main (stack bottom) → stack grows this way → top

sum(0) = 0 returned → 1 + 0 = 1.

main()sum(3)n=3: 3 + ?sum(2)n=2: 2 + ?sum(1)↩ return 1main (stack bottom) → stack grows this way → top

sum(1) = 1 returned → 2 + 1 = 3.

main()sum(3)n=3: 3 + ?sum(2)↩ return 3main (stack bottom) → stack grows this way → top

sum(2) = 3 returned → 3 + 3 = 6.

main()sum(3)↩ return 6main (stack bottom) → stack grows this way → top

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()main (stack bottom) → stack grows this way → top

main calls digitSum(472).

main()digitSum(472)main (stack bottom) → stack grows this way → top

Negatives become their absolute value: m = 472 (converting to long avoids overflow at the smallest int).

main()digitSum(472)main (stack bottom) → stack grows this way → top

A helper method does the real work.

main()digitSum(472)digitSumPos(472)main (stack bottom) → stack grows this way → top

472 < 10 → false: last digit 2, rest 47.

main()digitSum(472)digitSumPos(472)2 + ?main (stack bottom) → stack grows this way → top

472 % 10 = 2 is kept; a new call with 472 / 10 = 47.

main()digitSum(472)digitSumPos(472)2 + ?digitSumPos(47)main (stack bottom) → stack grows this way → top

47 < 10 → false: last digit 7, rest 4.

main()digitSum(472)digitSumPos(472)2 + ?digitSumPos(47)7 + ?main (stack bottom) → stack grows this way → top

47 % 10 = 7 is kept; a new call with 47 / 10 = 4.

main()digitSum(472)digitSumPos(472)2 + ?digitSumPos(47)7 + ?digitSumPos(4)main (stack bottom) → stack grows this way → top

4 < 10 → true: a single digit, return 4.

main()digitSum(472)digitSumPos(472)2 + ?digitSumPos(47)7 + ?digitSumPos(4)↩ return 4main (stack bottom) → stack grows this way → top

The subcall returned 4 → 7 + 4 = 11.

main()digitSum(472)digitSumPos(472)2 + ?digitSumPos(47)↩ return 11main (stack bottom) → stack grows this way → top

The subcall returned 11 → 2 + 11 = 13.

main()digitSum(472)digitSumPos(472)↩ return 13main (stack bottom) → stack grows this way → top

The helper returned 13; it is passed straight back.

main()digitSum(472)↩ return 13main (stack bottom) → stack grows this way → top

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()main (stack bottom) → stack grows this way → top0k1a2y3a4k

main calls isPal("kayak", 0, 4).

main()isPal(s, 0, 4)main (stack bottom) → stack grows this way → top0k1a2y3a4k▲ left▲ right

0 >= 4 → false.

main()isPal(s, 0, 4)main (stack bottom) → stack grows this way → top0k1a2y3a4k▲ left▲ right

'k' != 'k' → false: the ends match; continue inward.

main()isPal(s, 0, 4)main (stack bottom) → stack grows this way → top0k1a2y3a4k▲ left▲ right

Drop both ends: call isPal(s, 1, 3).

main()isPal(s, 0, 4)isPal(s, 1, 3)main (stack bottom) → stack grows this way → top0k1a2y3a4k▲ left▲ right

1 >= 3 → false.

main()isPal(s, 0, 4)isPal(s, 1, 3)main (stack bottom) → stack grows this way → top0k1a2y3a4k▲ left▲ right

'a' != 'a' → false: the ends match; continue inward.

main()isPal(s, 0, 4)isPal(s, 1, 3)main (stack bottom) → stack grows this way → top0k1a2y3a4k▲ left▲ right

Drop both ends: call isPal(s, 2, 2).

main()isPal(s, 0, 4)isPal(s, 1, 3)isPal(s, 2, 2)main (stack bottom) → stack grows this way → top0k1a2y3a4k▲ leftright

2 >= 2 → true: one character left in the middle → return true.

main()isPal(s, 0, 4)isPal(s, 1, 3)isPal(s, 2, 2)↩ return truemain (stack bottom) → stack grows this way → top0k1a2y3a4k▲ left▲ right

The subcall returned true; this frame returns the same value.

main()isPal(s, 0, 4)isPal(s, 1, 3)↩ return truemain (stack bottom) → stack grows this way → top0k1a2y3a4k▲ left▲ right

The subcall returned true; this frame returns the same value.

main()isPal(s, 0, 4)↩ return truemain (stack bottom) → stack grows this way → top0k1a2y3a4k

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()main (stack bottom) → stack grows this way → top

main calls gcd(48, 18).

main()gcd(48, 18)main (stack bottom) → stack grows this way → top

18 == 0 → false.

main()gcd(48, 18)main (stack bottom) → stack grows this way → top

48 % 18 = 12 → call gcd(18, 12) (the numbers shrink).

main()gcd(48, 18)gcd(18, 12)main (stack bottom) → stack grows this way → top

12 == 0 → false.

main()gcd(48, 18)gcd(18, 12)main (stack bottom) → stack grows this way → top

18 % 12 = 6 → call gcd(12, 6) (the numbers shrink).

main()gcd(48, 18)gcd(18, 12)gcd(12, 6)main (stack bottom) → stack grows this way → top

6 == 0 → false.

main()gcd(48, 18)gcd(18, 12)gcd(12, 6)main (stack bottom) → stack grows this way → top

12 % 6 = 0 → call gcd(6, 0) (the numbers shrink).

main()gcd(48, 18)gcd(18, 12)gcd(12, 6)gcd(6, 0)main (stack bottom) → stack grows this way → top

0 == 0 → true: base case, return 6.

main()gcd(48, 18)gcd(18, 12)gcd(12, 6)gcd(6, 0)↩ return 6main (stack bottom) → stack grows this way → top

The subcall returned 6; it is passed straight back.

main()gcd(48, 18)gcd(18, 12)gcd(12, 6)↩ return 6main (stack bottom) → stack grows this way → top

The subcall returned 6; it is passed straight back.

main()gcd(48, 18)gcd(18, 12)↩ return 6main (stack bottom) → stack grows this way → top

The subcall returned 6; it is passed straight back.

main()gcd(48, 18)↩ return 6main (stack bottom) → stack grows this way → top

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')

A321BCmoves: 0

Move 3 disks from A to C, with B as the helper. Rule: a larger disk never goes on a smaller one.

A321BCmoves: 0

hanoi(3, A, C, B): first the top 2 disks must move A → B (to the helper).

A321BCmoves: 0

hanoi(2, A, B, C): first the top disk must move A → C (to the helper).

A32BC1moves: 1

Move 1: disk 1 A → C. (the hanoi(0) calls return at once)

A3B2C1moves: 2

Move 2: disk 2 A → B.

A3B21Cmoves: 3

Move 3: disk 1 C → B.

AB21C3moves: 4

Move 4: disk 3 A → C.

AB21C3moves: 4

hanoi(2, B, C, A): first the top disk must move B → A (to the helper).

A1B2C3moves: 5

Move 5: disk 1 B → A.

A1BC32moves: 6

Move 6: disk 2 B → C.

ABC321moves: 7

Move 7: disk 1 A → C.

ABC321moves: 7

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)

main()main (stack bottom) → stack grows this way → top

2⁴ = 2 × 2³, so: power(base, n) = base × power(base, n − 1), power(base, 0) = 1.

main()power(2, 4)2 × ?main (stack bottom) → stack grows this way → top

4 == 0 → false: new call for 2 × power(2, 3).

main()power(2, 4)2 × ?power(2, 3)2 × ?main (stack bottom) → stack grows this way → top

3 == 0 → false: new call for 2 × power(2, 2).

main()power(2, 4)2 × ?power(2, 3)2 × ?power(2, 2)2 × ?main (stack bottom) → stack grows this way → top

2 == 0 → false: new call for 2 × power(2, 1).

main()power(2, 4)2 × ?power(2, 3)2 × ?power(2, 2)2 × ?power(2, 1)2 × ?main (stack bottom) → stack grows this way → top

1 == 0 → false: new call for 2 × power(2, 0).

main()power(2, 4)2 × ?power(2, 3)2 × ?power(2, 2)2 × ?power(2, 1)2 × ?power(2, 0)n=0main (stack bottom) → stack grows this way → top

0 == 0 → true: base case, return 1.

main()power(2, 4)2 × ?power(2, 3)2 × ?power(2, 2)2 × ?power(2, 1)2 × ?power(2, 0)↩ return 1main (stack bottom) → stack grows this way → top

power(2, 0) = 1 returned → 2 × 1 = 2.

main()power(2, 4)2 × ?power(2, 3)2 × ?power(2, 2)2 × ?power(2, 1)↩ return 2main (stack bottom) → stack grows this way → top

power(2, 1) = 2 returned → 2 × 2 = 4.

main()power(2, 4)2 × ?power(2, 3)2 × ?power(2, 2)↩ return 4main (stack bottom) → stack grows this way → top

power(2, 2) = 4 returned → 2 × 4 = 8.

main()power(2, 4)2 × ?power(2, 3)↩ return 8main (stack bottom) → stack grows this way → top

power(2, 3) = 8 returned → 2 × 8 = 16.

main()power(2, 4)↩ return 16main (stack bottom) → stack grows this way → top

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)

main()main (stack bottom) → stack grows this way → top

Idea: 2¹⁰ = (2⁵)², 2⁵ = (2²)² × 2. The exponent is halved on each call.

main()fastPow(2, 10)main (stack bottom) → stack grows this way → top

exp = 10 ≠ 0 → first fastPow(2, 5) (10 / 2 = 5).

main()fastPow(2, 10)fastPow(2, 5)main (stack bottom) → stack grows this way → top

exp = 5 ≠ 0 → first fastPow(2, 2) (5 / 2 = 2).

main()fastPow(2, 10)fastPow(2, 5)fastPow(2, 2)main (stack bottom) → stack grows this way → top

exp = 2 ≠ 0 → first fastPow(2, 1) (2 / 2 = 1).

main()fastPow(2, 10)fastPow(2, 5)fastPow(2, 2)fastPow(2, 1)main (stack bottom) → stack grows this way → top

exp = 1 ≠ 0 → first fastPow(2, 0) (1 / 2 = 0).

main()fastPow(2, 10)fastPow(2, 5)fastPow(2, 2)fastPow(2, 1)fastPow(2, 0)main (stack bottom) → stack grows this way → top

exp == 0: return 1.

main()fastPow(2, 10)fastPow(2, 5)fastPow(2, 2)fastPow(2, 1)fastPow(2, 0)↩ return 1main (stack bottom) → stack grows this way → top

half = 1; 1 is odd → 1 × 1 × 2 = 2.

main()fastPow(2, 10)fastPow(2, 5)fastPow(2, 2)fastPow(2, 1)↩ return 2main (stack bottom) → stack grows this way → top

half = 2; 2 is even → 2 × 2 = 4.

main()fastPow(2, 10)fastPow(2, 5)fastPow(2, 2)↩ return 4main (stack bottom) → stack grows this way → top

half = 4; 5 is odd → 4 × 4 × 2 = 32.

main()fastPow(2, 10)fastPow(2, 5)↩ return 32main (stack bottom) → stack grows this way → top

half = 32; 10 is even → 32 × 32 = 1024.

main()fastPow(2, 10)↩ return 1024main (stack bottom) → stack grows this way → top

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)

021528312416523638756a

Recursion instead of a loop: each call recurses on half the range.

021528312416523638756▲ lo▲ hi▲ mida

0 <= 7; mid = 3, a[mid] = 12.

021528312416523638756▲ lo▲ hia

12 < 38 → right half: search(a, 38, 4, 7).

021528312416523638756▲ lo▲ hi▲ mida

4 <= 7; mid = 5, a[mid] = 23.

021528312416523638756▲ lo▲ hia

23 < 38 → right half: search(a, 38, 6, 7).

021528312416523638756▲ lomid▲ hia

6 <= 7; mid = 6, a[mid] = 38.

021528312416523638756▲ lomid▲ hia

38 == 38 → return 6 (base case).

021528312416523638756▲ mida

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.

[5, 2, 4, 1][5, 2][4, 1][5][2][4][1][2, 5][1, 4][1, 2, 4, 5]splitmergegray: split · colored: merge

Examples · Step through the code

Reversing a String Recursively

main()main (stack bottom) → stack grows this way → top

reverse(s) = reverse(everything but the first character) + the first character.

main()reverse("abc")? + "a"main (stack bottom) → stack grows this way → top

reverse("bc") is called; 'a' waits to be appended at the end.

main()reverse("abc")? + "a"reverse("bc")? + "b"main (stack bottom) → stack grows this way → top

reverse("c") is called; 'b' waits to be appended at the end.

main()reverse("abc")? + "a"reverse("bc")? + "b"reverse("c")s="c"main (stack bottom) → stack grows this way → top

Length 1 ≤ 1 → base case, "c" is returned.

main()reverse("abc")? + "a"reverse("bc")? + "b"reverse("c")↩ return "c"main (stack bottom) → stack grows this way → top

"c" + 'b' = "cb".

main()reverse("abc")? + "a"reverse("bc")↩ return "cb"main (stack bottom) → stack grows this way → top

"cb" + 'a' = "cba".

main()reverse("abc")↩ return "cba"main (stack bottom) → stack grows this way → top

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()main (stack bottom) → stack grows this way → top

main calls subsets(a, 0, chosen) with an empty list. Each element has two choices: include / exclude.

main()subsets(i=0)chosen (one list shared by all frames)[]main (stack bottom) → stack grows this way → top

i = 0: the array isn't finished (0 ≠ 2). First the include 1 branch.

main()subsets(i=0)chosen (one list shared by all frames)[1]main (stack bottom) → stack grows this way → top

chosen.add(1): the list is now [1].

main()subsets(i=0)subsets(i=1)chosen (one list shared by all frames)[1]main (stack bottom) → stack grows this way → top

New frame i = 1: decide on 2; include it first.

main()subsets(i=0)subsets(i=1)chosen (one list shared by all frames)[1, 2]main (stack bottom) → stack grows this way → top

chosen.add(2): the list is [1, 2].

main()subsets(i=0)subsets(i=1)subsets(i=2)chosen (one list shared by all frames)[1, 2]main (stack bottom) → stack grows this way → top

i = 2 = a.length: base case. Print the subset: [1, 2].

main()subsets(i=0)subsets(i=1)chosen (one list shared by all frames)[1]main (stack bottom) → stack grows this way → top

On the way back, chosen.remove(...) takes 2 out (backtracking) → [1].

main()subsets(i=0)subsets(i=1)subsets(i=2)chosen (one list shared by all frames)[1]main (stack bottom) → stack grows this way → top

The exclude 2 branch reaches a leaf: [1].

main()subsets(i=0)chosen (one list shared by all frames)[]main (stack bottom) → stack grows this way → top

subsets(i=1) is done; remove takes 1 out → [].

main()subsets(i=0)subsets(i=1)chosen (one list shared by all frames)[]main (stack bottom) → stack grows this way → top

The exclude 1 branch: a new frame with i = 1.

main()subsets(i=0)subsets(i=1)chosen (one list shared by all frames)[2]main (stack bottom) → stack grows this way → top

chosen.add(2): the list is [2].

main()subsets(i=0)subsets(i=1)subsets(i=2)chosen (one list shared by all frames)[2]main (stack bottom) → stack grows this way → top

Leaf: [2] is printed.

main()subsets(i=0)subsets(i=1)chosen (one list shared by all frames)[]main (stack bottom) → stack grows this way → top

remove takes 2 out → [].

main()subsets(i=0)subsets(i=1)subsets(i=2)chosen (one list shared by all frames)[]main (stack bottom) → stack grows this way → top

Last leaf: the empty set [].

main()chosen (one list shared by all frames)[]main (stack bottom) → stack grows this way → top

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.
main()forever(0)return point savedforever(1)return point savedforever(2)return point savedforever(3)forever(4)forever(5)stack limitStackOverflowError

The Call Stack · Step through the code

Code Trace: StackOverflowError

main()main (stack bottom) → stack grows this way → top

main calls forever(0).

main()forever(0)main (stack bottom) → stack grows this way → top

First frame. With no base case, forever(1) is called at once.

main()forever(0)forever(1)main (stack bottom) → stack grows this way → top

The second frame; the previous one is still on the stack.

main()forever(0)forever(1)forever(2)main (stack bottom) → stack grows this way → top

The third frame. No call returns, so no frame is removed.

main()forever(0)forever(1)forever(2)…main (stack bottom) → stack grows this way → top

This goes on, but stack memory is limited (typically tens of thousands of calls).

main()forever(0)forever(1)forever(2)…forever(k)stack fullmain (stack bottom) → stack grows this way → top

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.
recursiveiterativemain()factorial(4)factorial(3)factorial(2)factorial(1)main()factorialLoop(4)i, result in the same frameupdated each pass5 frames: O(n) stack2 frames: O(1) extra stack

Efficiency

Comparing Factorials

PropertyRecursiveIterative
Time complexityO(n)O(n)
Extra stackO(n)O(1)
FlowClose to the definitionExplicit counter
Depth riskYesNo
recursive factorial(4)factorial(1)factorial(2)factorial(3)factorial(4)main()4 framesextra stack: n frames → O(n)iterative factorialLoop(4)i: 2 → 3 → 4, result: 2 → 6 → 24factorialLoop(4)n, i, resultmain()extra stack: one frame → O(1)

Efficiency · Step through the code

Comparison: Iterative factorial(4)

main()main (stack bottom) → stack grows this way → top

main calls factorialLoop(4).

main()factorialLoop(4)n=4main (stack bottom) → stack grows this way → top

A single frame opens; result = 1.

main()factorialLoop(4)i=2, result=1main (stack bottom) → stack grows this way → top

2 <= 4 → true

main()factorialLoop(4)i=2, result=2main (stack bottom) → stack grows this way → top

result *= 2 → 1 × 2 = 2. No new frame opened.

main()factorialLoop(4)i=3, result=2main (stack bottom) → stack grows this way → top

i++ → 3 <= 4 → true

main()factorialLoop(4)i=3, result=6main (stack bottom) → stack grows this way → top

result *= 3 → 2 × 3 = 6. No new frame opened.

main()factorialLoop(4)i=4, result=6main (stack bottom) → stack grows this way → top

i++ → 4 <= 4 → true

main()factorialLoop(4)i=4, result=24main (stack bottom) → stack grows this way → top

result *= 4 → 6 × 4 = 24. No new frame opened.

main()factorialLoop(4)i=5, result=24main (stack bottom) → stack grows this way → top

i++ → 5 <= 4 → false: the loop ends.

main()factorialLoop(4)i=5, result=24main (stack bottom) → stack grows this way → top

return 24.

main()factorialLoop(4)↩ return 24main (stack bottom) → stack grows this way → top

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

f(5)f(4)f(3)f(2)f(1)f(0)f(1)f(2)f(1)f(0)f(3)f(2)f(1)f(0)f(1)
  • 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).

f(4)

fib(4) called: 4 <= 1 → false.

f(4)f(3)

fib(3) called: 3 <= 1 → false.

f(4)f(3)f(2)

fib(2) called: 2 <= 1 → false.

f(4)f(3)f(2)f(1)

fib(1) called: 1 <= 1 → true, return 1.

f(4)f(3)f(2)f(1)=1f(0)

fib(0) called: 0 <= 1 → true, return 0.

f(4)f(3)f(2)=1f(1)=1f(0)=0

Both subresults ready: 1 + 0 = 1, return.

f(4)f(3)f(2)=1f(1)=1f(0)=0f(1)

fib(1) called: 1 <= 1 → true, return 1.

f(4)f(3)=2f(2)=1f(1)=1f(0)=0f(1)=1

Both subresults ready: 1 + 1 = 2, return.

f(4)f(3)=2f(2)=1f(1)=1f(0)=0f(1)=1f(2)

fib(2) called: 2 <= 1 → false. Repeat: f(2) is computed again!

f(4)f(3)=2f(2)=1f(1)=1f(0)=0f(1)=1f(2)f(1)

fib(1) called: 1 <= 1 → true, return 1.

f(4)f(3)=2f(2)=1f(1)=1f(0)=0f(1)=1f(2)f(1)=1f(0)

fib(0) called: 0 <= 1 → true, return 0.

f(4)f(3)=2f(2)=1f(1)=1f(0)=0f(1)=1f(2)=1f(1)=1f(0)=0

Both subresults ready: 1 + 0 = 1, return.

f(4)=3f(3)=2f(2)=1f(1)=1f(0)=0f(1)=1f(2)=1f(1)=1f(0)=0

Both subresults ready: 2 + 1 = 3, return.

f(4)=3f(3)=2f(2)=1f(1)=1f(0)=0f(1)=1f(2)=1f(1)=1f(0)=0

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.
f(5)f(3) ✓f(4)f(2) ✓f(3)f(1)f(2)f(0)f(1)✓ = read from memo, subtree not expanded

Improvement · Step through the code

Code Trace: Memoized fib(5)

001020304050memo0 and 1 are base cases (unused)calls: 0

A 6-cell memo array; 0 = not computed yet.

001020304050memo0 and 1 are base cases (unused)calls: 1

fib(5): memo[5] == 0 → not yet known; compute it.

001020304050memo0 and 1 are base cases (unused)calls: 2

fib(4): memo[4] == 0 → not yet known; compute it.

001020304050memo0 and 1 are base cases (unused)calls: 3

fib(3): memo[3] == 0 → not yet known; compute it.

001020304050memo0 and 1 are base cases (unused)calls: 4

fib(2): memo[2] == 0 → not yet known; compute it.

001020304050memo0 and 1 are base cases (unused)calls: 5

fib(1): 1 <= 1 → true, return 1.

001020304050memo0 and 1 are base cases (unused)calls: 6

fib(0): 0 <= 1 → true, return 0.

001021304050memo0 and 1 are base cases (unused)calls: 6

memo[2] = 1 + 0 = 1 is stored and returned.

001021304050memo0 and 1 are base cases (unused)calls: 7

fib(1): 1 <= 1 → true, return 1.

001021324050memo0 and 1 are base cases (unused)calls: 7

memo[3] = 1 + 1 = 2 is stored and returned.

001021324050memo0 and 1 are base cases (unused)✓ from memocalls: 8

fib(2): memo[2] = 1 != 0 → return 1 without computing.

001021324350memo0 and 1 are base cases (unused)calls: 8

memo[4] = 2 + 1 = 3 is stored and returned.

001021324350memo0 and 1 are base cases (unused)✓ from memocalls: 9

fib(3): memo[3] = 2 != 0 → return 2 without computing.

001021324355memo0 and 1 are base cases (unused)calls: 9

memo[5] = 3 + 2 = 5 is stored and returned.

001021324355memo0 and 1 are base cases (unused)calls: 9

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
normaltailfactorial(4)fact(4, 1)factorial(3)fact(3, 4)factorial(2)fact(2, 12)factorial(1)fact(1, 24)24 = 4 × 66 = 3 × 22 = 2 × 1on return:the base case returns 24; nothing is left to multiply, 24 passes back as is

Improvement · Step through the code

Code Trace: fact(4, 1)

main()main calls fact(4, 1); acc starts at 1main (stack bottom) → stack grows this way → top

main calls fact(4, 1): the second parameter, acc, starts at 1.

main()fact(4, 1)acc=1main (stack bottom) → stack grows this way → top

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.

main()fact(4, 1)acc=1fact(3, 4)acc=4main (stack bottom) → stack grows this way → top

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.

main()fact(4, 1)acc=1fact(3, 4)acc=4fact(2, 12)acc=12main (stack bottom) → stack grows this way → top

Next call: fact(1, 24). The stack still grows by one frame per call.

main()fact(4, 1)acc=1fact(3, 4)acc=4fact(2, 12)acc=12fact(1, 24)acc=24main (stack bottom) → stack grows this way → top

1 <= 1 → true: base case, return acc → 24. Tail recursion or not, 5 frames (main + 4) piled up: Java has no tail-call optimization.

main()← returned 24main (stack bottom) → stack grows this way → top

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

long overflow

factorial(20) → 2432902008176640000 (correct).
factorial(21) → -4249290049419214848
No exception is thrown; the value silently wraps. A long holds at most 9223372036854775807.

Negative exponent

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)

nfib(n) recursive: number of callsfib(n) iterative: number of passes
1017710
202189120
30269253730

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.
DepthEventValue
0sum(2) called
1  sum(1) called
2    sum(0) called
2    sum(0) returned0
1  sum(1) returned1
0sum(2) returned3

Summary

Chapter Summary

Structure

A base case + a recursive case that shrinks the problem.

Call stack

Each call opens a frame; after the base case the frames close in reverse order.

Cost

Linear recursion uses O(n) stack; a loop usually does the same job in O(1).

Memoization

Storing repeated subproblem results takes fib from exponential to O(n).

Summary

Review Questions

  1. What happens without a base case?
  2. Why does the call stack unwind in reverse order?
  3. How much extra stack does recursive factorial use?
  4. Why is naive Fibonacci slow?
  5. Why doesn't tail recursion make Java stack-safe?
Answers
  1. The calls never end; the stack fills up and a StackOverflowError occurs.
  2. Each call waits for the result of the call opened after it; the last frame opened finishes first.
  3. n frames → O(n).
  4. It recomputes the same subproblems (f(2), f(3)…) over and over; the number of calls grows exponentially.
  5. The JVM doesn't guarantee tail-call optimization; every call still opens a new frame.

Summary

Exercises

  1. Write the sum of an array recursively: sum(a, i) = a[i] + sum(a, i + 1).
  2. Count the digits of a number recursively (digits(472) = 3).
  3. Write a toBinary(n) method that converts a decimal number to binary recursively (13 → "1101").
  4. How many moves does Hanoi need for n = 4? Check it with the program.
  5. Write the base cases for choose(n, k) = choose(n − 1, k − 1) + choose(n − 1, k); speed it up with memoization.
  6. 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).

The End

Chapter 12: Recursion
Previous: Chapter 11: Strings
1 / 1Sercan KÜLCÜ. All rights reserved.