Esc
  • Loading…
↑ ↓ to moveEnter to openEsc to close

Recursion & Backtracking

Breaking problems into smaller versions of themselves, and undoing choices that don't work out.

  • 1 Lesson

Dry-run engine

Factorial (Recursive)

Every call gets its own stack frame; recursion is just frames piling up and then unwinding.

O(n) Stack Memory
Input · Call
fact(4)
Output · Returns
Press play to run it
How it works

fact(n) returns 1 when n <= 1; otherwise it calls fact(n - 1) and multiplies the result by n. Every call still waiting on another call keeps its own frame on the stack.

call_stack · grows ↓

  • sp0x7ff0
  • Depth1 frame
  • Pending4 × fact(3)
  • Returned—

fact(4) pushes its frame at 0x7ff0. 4 > 1, so it can't answer yet: it pauses at 4 * fact(3) and calls fact(3). Its frame keeps n = 4 alive until then.

1 / 8

Course Contents