Command Palette

Search for a command to run...

Module 12

Recursion

Solve a problem using a smaller copy of itself: pick a base case, trust the recursive call, and learn what it costs in time and stack.

Intermediate 4 lessons 5 problems ~50 min of lessons

Recursion is a way of thinking before it's a coding technique: if you can describe the answer for size n in terms of the answer for a smaller size, the code almost writes itself. Trees, backtracking, divide and conquer and dynamic programming all build on it.

This module covers the leap of faith (trusting the smaller call), what the call stack really does, how to estimate cost with a recursion tree, and when to turn recursion into a loop because Java has no tail-call optimisation.

Best after: Java for DSA

Part 1

Learn the ideas

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. The same problem in three costs: exponential recursion, memoised recursion, and an O(1)-space loop.

  2. Fast exponentiation: xⁿ = (x^(n/2))², so the recursion depth is log n, not n.

  3. A loop rewritten as recursion: swap the ends, then recurse on the inside. Shows how depth becomes stack space.

  4. The classic leap of faith: to move n discs, trust that you can move n − 1 discs, twice.

  5. Recurse on the structure instead of building it: each symbol depends only on its parent in the previous row.