Practice: recursion
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
This practice lesson brings together every recursion pattern from Module 5.9: winding vs unwinding (1 .. n and n .. 1), digit peeling and accumulators, the classic Tower of Hanoi puzzle, and generating all binary strings of length n (your bridge into Module 5.10 Backtracking!).
Print 1 to n and n to 1 without loops
Where you place the action relative to the recursive call controls the order: before the call it runs from n down to 1, after the call it runs from 1 up to n.
static void printNto1(int n) { if (n == 0) return; System.out.println(n); // before the call: prints 3, 2, 1 printNto1(n - 1);}
static void print1toN(int n) { if (n == 0) return; print1toN(n - 1); System.out.println(n); // after the call: prints 1, 2, 3}- Before the recursive call (winding):
printNto1(n)printsn, then callsprintNto1(n - 1). - After the recursive call (unwinding):
print1toN(n)callsprint1toN(n - 1), then printsn. - Both take O(n) time and O(n) stack space.
Sum of digits and reverse a number
For a non-negative integer n with d = ⌊ log₁₀ n ⌋ + 1 digits:
- Sum of digits:
n < 10 ? n : (n % 10) + sumDigits(n / 10). - Reverse a number: pass an accumulator
revinitialized to0:
public class DigitRecursion { static int sumDigits(int n) { return n < 10 ? n : (n % 10) + sumDigits(n / 10); }
static int reverse(int n, int rev) { return n == 0 ? rev : reverse(n / 10, rev * 10 + n % 10); }
public static void main(String[] args) { System.out.println(sumDigits(4096)); // 4 + 0 + 9 + 6 System.out.println(reverse(1234, 0)); }}19 4321
n == 0 ? rev : reverse(n / 10, rev * 10 + n % 10). Both run in O(d) = O(log₁₀ n) time and stack space.
Tower of Hanoi
In the Tower of Hanoi puzzle, you have three pegs (A = source, B = auxiliary, C = destination) and n disks of sizes 1 .. n stacked on A from largest at the bottom to smallest at the top.
- Base case: if
n == 1, move disk 1 directly fromsrctodst. - Move the top
n - 1disks fromsrctoaux(usingdstas temporary peg). - Move the largest disk
ndirectly fromsrctodst. - Move the
n - 1disks fromauxtodst(usingsrcas temporary peg).
Example 1 · Tower of Hanoi step-by-step moves and move count (2^n - 1)
public class TowerOfHanoiDemo { public static int hanoi(int n, char src, char aux, char dst) { if (n == 1) { System.out.println("Move disk 1 from " + src + " to " + dst); return 1; } int m1 = hanoi(n - 1, src, dst, aux); System.out.println("Move disk " + n + " from " + src + " to " + dst); int m2 = hanoi(n - 1, aux, src, dst); return m1 + 1 + m2; }
public static void main(String[] args) { int moves = hanoi(3, 'A', 'B', 'C'); System.out.println("Total moves: " + moves); }}Move disk 1 from A to C Move disk 2 from A to B Move disk 1 from C to B Move disk 3 from A to C Move disk 1 from B to A Move disk 2 from B to C Move disk 1 from A to C Total moves: 7
What this code does
- Moving 3 disks from A to C first moves the top 2 disks to B (3 moves), moves disk 3 to C (1 move), and moves the 2 disks from B to C (3 moves).
- Total moves = 3 + 1 + 3 = 7 = 2^3 - 1.
You may move only 1 disk at a time, and you may never place a larger disk on top of a smaller disk. How do you move n disks from src to dst using aux? Trust the Recursive Leap of Faith: Notice the recurrence: T(n) = 2T(n - 1) + 1 with T(1) = 1, which solves to 2ⁿ - 1 moves (O(2ⁿ) time and O(n) stack space)!
Generate all binary strings of length n
To generate all 2ⁿ binary strings of length n in order ("000", "001", ..., "111"), place '0' then '1' at each position and recurse on the next one.
Example 2 · Generating all binary strings of length n using a char[] buffer
import java.util.ArrayList;import java.util.List;
public class GenerateBinaryStringsDemo { public static List<String> binaryStrings(int n) { List<String> res = new ArrayList<>(); generate(new char[n], 0, res); return res; }
private static void generate(char[] buf, int idx, List<String> res) { if (idx == buf.length) { res.add(new String(buf)); return; } buf[idx] = '0'; generate(buf, idx + 1, res); buf[idx] = '1'; generate(buf, idx + 1, res); }
public static void main(String[] args) { System.out.println(binaryStrings(3)); }}[000, 001, 010, 011, 100, 101, 110, 111]
What this code does
- Reusing a single char[n] buffer across the recursion uses O(n) working memory and avoids creating intermediate String objects at internal nodes.
- Writing '0' before '1' at each index naturally produces all 2^n strings in sorted lexicographical order.
Example 3 · Generating binary strings of length n with NO consecutive 1s
import java.util.ArrayList;import java.util.List;
public class NoConsecutiveOnesDemo { public static void generateValid(char[] buf, int idx, List<String> res) { if (idx == buf.length) { res.add(new String(buf)); return; } // Choice 1: '0' is always allowed buf[idx] = '0'; generateValid(buf, idx + 1, res);
// Choice 2: '1' is allowed only if the previous character was NOT '1' if (idx == 0 || buf[idx - 1] != '1') { buf[idx] = '1'; generateValid(buf, idx + 1, res); } }
public static void main(String[] args) { List<String> res = new ArrayList<>(); generateValid(new char[3], 0, res); System.out.println(res + " (count=" + res.size() + ")"); }}[000, 001, 010, 100, 101] (count=5)
What this code does
- Checking if (idx == 0 || buf[idx - 1] != '1') prunes invalid branches before they even recurse!
- Notice that for n = 1, 2, 3, the counts of valid strings are 2, 3, 5 (Fibonacci numbers!).
- At position
idx(from0ton - 1) you have two choices: place'0'and recurse onidx + 1, then place'1'and recurse onidx + 1. - Base case: when
idx == n, thechar[] bufholds a complete string; addnew String(buf)to the result list. - Cost: 2ⁿ leaves, each doing O(n) work to build the string = O(n · 2ⁿ) time and O(n) auxiliary stack space.
Trace first, then write
Whenever a recursive problem feels tricky, trace n = 1 and n = 2 by hand on paper before writing code. Write down: (1) the exact meaning of solve(state), (2) the base case for the smallest input, and (3) how solve(state) combines its recursive subcalls.
Finish up
Mark complete & continue
Next: What backtracking is