A recursive method solves a problem by calling itself on a smaller version of the same problem, until it reaches a case small enough to answer directly. Recursion makes some problems, such as walking folders, generating permutations or exploring choices, much simpler to write. This lesson goes beyond the basics: why naive recursion can be painfully slow, how memoization fixes it, and how backtracking explores every possibility.
In this lesson you will learn
- The two parts of every recursive method: base case and recursive case
- Why naive Fibonacci makes millions of calls
- Speeding up recursion with memoization
- Backtracking: permutations and subset sums
- What causes a
StackOverflowError
You should know methods, where recursion was first introduced, and HashMap.
Base Cases, Repeated Work and Memoization
import java.util.HashMap;
import java.util.Map;
public class Main {
static int calls = 0;
// Plain recursion: recalculates the same values again and again
static long fib(int n) {
calls++;
if (n <= 1) return n; // base case
return fib(n - 1) + fib(n - 2); // recursive case
}
// Memoization: remember answers already worked out
static Map<Integer, Long> memo = new HashMap<>();
static long fibMemo(int n) {
calls++;
if (n <= 1) return n;
if (memo.containsKey(n)) return memo.get(n);
long result = fibMemo(n - 1) + fibMemo(n - 2);
memo.put(n, result);
return result;
}
// Recursion on a string: is it a palindrome?
static boolean isPalindrome(String s) {
if (s.length() <= 1) return true;
if (s.charAt(0) != s.charAt(s.length() - 1)) return false;
return isPalindrome(s.substring(1, s.length() - 1));
}
public static void main(String[] args) {
calls = 0;
System.out.println("fib(30) = " + fib(30) + " using " + calls + " calls");
calls = 0;
System.out.println("fibMemo(30) = " + fibMemo(30) + " using " + calls + " calls");
System.out.println("fibMemo(90) = " + fibMemo(90));
for (String w : new String[] {"level", "racecar", "java"}) {
System.out.println(w + " palindrome? " + isPalindrome(w));
}
}
}
Output
fib(30) = 832040 using 2692537 calls
fibMemo(30) = 832040 using 59 calls
fibMemo(90) = 2880067194370816120
level palindrome? true
racecar palindrome? true
java palindrome? false
- Every recursive method needs a base case that returns without calling itself (
n <= 1), and a recursive case that moves closer to it (n − 1andn − 2). - Naive
fib(30)makes 2,692,537 calls.fib(28)is calculated twice,fib(27)three times, and the repeats grow exponentially. - Memoization stores each answer in a map the first time it is worked out.
fibMemo(30)needs only 59 calls, andfibMemo(90)answers instantly. Naivefib(90)would take years. - The palindrome check compares the first and last characters, then calls itself on the middle. A string of length 0 or 1 is the base case.
Backtracking
Backtracking builds a solution one choice at a time. If a choice leads somewhere useful, it continues; when it reaches the end or a dead end, it undoes the last choice and tries the next one.
import java.util.ArrayList;
import java.util.List;
public class Main {
// Backtracking: choose, explore, un-choose
static void permutations(String prefix, String rest, List<String> out) {
if (rest.isEmpty()) {
out.add(prefix);
return;
}
for (int i = 0; i < rest.length(); i++) {
String remaining = rest.substring(0, i) + rest.substring(i + 1);
permutations(prefix + rest.charAt(i), remaining, out);
}
}
// All subsets of coins whose values add up to a target
static void subsets(int[] coins, int i, int target, List<Integer> chosen) {
if (target == 0) {
System.out.println(" " + chosen);
return;
}
if (i == coins.length || target < 0) return;
chosen.add(coins[i]); // choose coins[i]
subsets(coins, i + 1, target - coins[i], chosen);
chosen.remove(chosen.size() - 1); // un-choose it
subsets(coins, i + 1, target, chosen); // skip coins[i]
}
static int depth(int n) {
return depth(n + 1); // no base case!
}
public static void main(String[] args) {
List<String> perms = new ArrayList<>();
permutations("", "ABC", perms);
System.out.println("Permutations of ABC: " + perms);
System.out.println("Coin sets that make 10:");
subsets(new int[] {2, 3, 5, 7, 8}, 0, 10, new ArrayList<>());
try {
depth(0);
} catch (StackOverflowError e) {
System.out.println("No base case: " + e.getClass().getSimpleName());
}
}
}
Output
Permutations of ABC: [ABC, ACB, BAC, BCA, CAB, CBA]
Coin sets that make 10:
[2, 3, 5]
[2, 8]
[3, 7]
No base case: StackOverflowError
permutationspicks each remaining letter in turn as the next letter, then calls itself on what is left. Three letters give 3 × 2 × 1 = 6 orders.subsetsmakes a yes/no decision for each coin: take it (chosen.add) or skip it. After exploring “take”, it removes the coin again (chosen.remove) before exploring “skip”. This undo step is what makes it backtracking.- The
target < 0check stops exploring as soon as the total is too big. Cutting off hopeless branches early is called pruning, and it can make backtracking vastly faster. depthhas no base case, so it calls itself until the call stack runs out of space and Java throwsStackOverflowError.
Recursion or a Loop?
| Use recursion when | Use a loop when |
|---|---|
| The data is a tree or nested structure (folders, JSON, expressions) | You walk a list or count from 1 to n |
| You explore choices (permutations, puzzles, mazes) | The depth could be very large (millions of steps) |
| Divide-and-conquer algorithms (merge sort, quick sort, binary search) | Speed and memory matter most |
Each recursive call uses a frame on the call stack. Java does not optimise tail calls, so very deep recursion fails where a loop would not. The default stack fits thousands to tens of thousands of simple calls, depending on the JVM and settings.
Common Mistakes
- Missing or unreachable base case, leading to
StackOverflowError. - Not moving towards the base case, such as calling
f(n)from insidef(n). - Forgetting to undo a choice in backtracking, so later branches see leftover values.
- Recomputing the same subproblems without memoization.
Practice Exercises
Exercise 1. Write a recursive method that returns the sum of the digits of a non-negative int.
Show answer
static int digitSum(int n) {
if (n < 10) return n;
return n % 10 + digitSum(n / 10);
}
// digitSum(4096) == 19
Exercise 2. Write a recursive method that counts the ways to climb n stairs taking 1 or 2 steps at a time, with memoization.
Show answer
static Map<Integer, Long> seen = new HashMap<>();
static long ways(int n) {
if (n <= 1) return 1;
if (seen.containsKey(n)) return seen.get(n);
long w = ways(n - 1) + ways(n - 2);
seen.put(n, w);
return w;
}
// ways(10) == 89
Frequently Asked Questions
Can every recursive method be written as a loop?
Yes. Any recursion can be turned into a loop with your own stack data structure. For tree-like problems the recursive version is usually much shorter and clearer.
What is the difference between memoization and dynamic programming?
Memoization keeps the recursive code and caches results (“top-down”). Dynamic programming often fills a table with a loop from the smallest case upwards (“bottom-up”). Both avoid repeating work.
Summary
- Every recursive method needs a base case and a step towards it.
- Repeated subproblems make naive recursion slow; memoization fixes that.
- Backtracking tries a choice, explores, then undoes it.
- Very deep recursion overflows the stack; use a loop there.
