The mechanism that finally made recursion practical.
That mechanism is the call stack. Once LISP
(John McCarthy, 1958) and ALGOL 60 built it
in, recursive procedures went from mathematical curiosity to a normal
tool - because so many real problems are naturally defined in terms of
smaller versions of themselves.
A Motivating Example: Defining By Itself
The oldest recursive idea in this course, written out plainly.
- an answer given directly, no further self-reference.
Unwinding
The same definition, expanded one step at a time.
Notice the shape: one case that answers directly, one case that
answers in terms of a smaller version of the same question. That shape
is what today formalizes.
Recursion: Definition
A mathematical habit centuries old, a warm-up you just ran by hand, and a frozen demo all point at one idea. Here it is, precisely (CLRS - Cormen/Leiserson/Rivest/Stein's Introduction to Algorithms, 4th ed, §4.3-4.5).
A recursive algorithm solves a problem by solving one or more
smaller instances of the same problem (the recursive case),
until it reaches an instance small enough to answer directly (the base case).
Recursion: Base Case vs. Recursive Case
The definition, unpacked into its two working parts.
Base case: the smallest input the algorithm can answer with no further self-call - it is what stops the recursion.
Recursive case: expresses the answer for a bigger input in terms of the answer for a smaller one.
Every recursive algorithm needs both. Miss the base case, and the recursion never stops.
Key Words Today
Recurrence relation: a formula for an algorithm's cost, written in terms of its own cost on smaller input.
Substitution method: guess the closed-form answer to a recurrence, then prove the guess by induction.
Recursion tree: a diagram of every recursive call, used to sum an algorithm's total cost level by level.
Master Theorem: a shortcut for solving the common divide-and-conquer recurrence shape (previewed today, proven Week 9).
Recursion vs. Iteration: Same Idea, Two Forms
Same answer, two different ways to describe "what's left to do."
Recursive
FACTORIAL(n):
if n == 0:
return 1
return n * FACTORIAL(n - 1)
Iterative
FACTORIAL(n):
result = 1
for i = 1 to n:
result = result * i
return result
Both compute the same answer. The recursive version trades an
explicit loop counter for the call stack keeping track of "what's left."
Call-stack tracing · worked example
Tracing the Call Stack: factorial(4)
Five frames stack up before a single multiplication happens - then everything unwinds.
GoalTrace factorial(4) all the way down to the base case, and all the way back up.
factorial(4) = 4×6 = 24, final answer. The base case is what the whole unwind is built from - it bounds how deep the stack could ever grow.
✓
Conclusionfactorial(4) = 24, traced through 5 stacked frames and back.
💡
Key takeawayAt the moment factorial(0) returns, four frames are still waiting - factorial(1) through factorial(4) - each paused on its own multiplication until the call below it finishes.
Another Conversion: Summing 1 to
Same recursive/iterative shape as factorial - a different base operation, traced in one line.
Recursive
SUM(n):
if n == 0:
return 0
return n + SUM(n - 1)
Iterative
SUM(n):
total = 0
for i = 1 to n:
total = total + i
return total
Same recurrence shape as factorial: . Five
frames deep, same as factorial(4) - the base case SUM(0) = 0 is
what the whole chain unwinds from.
Recurrence Relations: Writing Cost as a Formula
Now let's measure the trace we just watched, not just narrate it.
Each call to factorial(n) does work of its own (one comparison, one multiply) plus whatever factorial(n-1) costs.
This is the "self-referential formula" that stumped us at the end of last week - a cost defined in terms of itself, on smaller input.
Not Every Recursion Shrinks by One
A second shape, distinct from `factorial`'s.
Not every recursive algorithm shrinks by 1 each call. Algorithms that
split their input in half give a different shape:
We'll meet this exact recurrence again in Week 6 - it is merge sort's cost.
A Quick Primer: Mathematical Induction
Dominoes, not magic - and it's about to become this course's main proof tool.
To prove a statement true for every whole number , two steps
replace checking each one at a time:
Base case: true for the smallest (the first domino falls).
Inductive step: if it's true for some , it must also be true
for (each falling domino knocks over the next one) - like
climbing a staircase, knowing each step leads to the next.
This is exactly what the substitution method, next, does: guess the
closed-form answer, then use induction to prove the guess is right.
Substitution method · worked example 1 of 2 (moderate)
Solving by Substitution
Guess the answer, then prove the guess by induction.
GoalProve T(n) = O(n) for T(n) = T(n−1) + d, some constant d.
1
Guess
Formally: T(n) ≤ cn for a constant c and all n ≥ n0.
→
2
Base case
True for small n once c is chosen large enough to cover T(n0).
→
3
Inductive step
Assume T(n−1) ≤ c(n−1). Then T(n) = T(n−1)+d ≤ c(n−1)+d = cn−c+d ≤ cn whenever c ≥ d.
→
4
Conclusion
Choosing c=d makes the last step hold. T(n)=O(n) - matching the 4-frame trace hand-counted for factorial(4) above.
✓
ConclusionT(n) = T(n−1) + d solves to T(n) = O(n).
💡
Key takeawaySubstitution proves a guess by induction - base case, then an inductive step that carries it for every larger n.
Substitution method · worked example 2 of 2 (harder)
A New Recurrence: ,
Same method, a concrete constant this time - and a limit on what substitution can actually do for you.
GoalFind a constant c that makes the inductive step hold, then see what substitution cannot supply.
1
Guess
T(n) = O(n), i.e. T(n) ≤ cn for n ≥ n0.
→
2
Inductive step
T(n) = T(n−1)+3 ≤ c(n−1)+3 = cn−c+3 ≤ cn exactly when c ≥ 3. Any c ≥ 3 works - choose c=3.
→
3
Base case
T(0)=1 ≤ c·n0 for a suitable n0 (e.g. n0=1, c=3: 1 ≤ 3, holds).
★
What substitution can't do
The method only verifies a guess - it never tells you what to guess. That's exactly why the recursion-tree method, next, is useful even when substitution is available: it can suggest a guess to check.
log₂n levels down: 3log₂n = nlog₂3 ≈ n1.585 leaves, each O(1). The sum is dominated by this bottom level.
★
Result
T(n) = Θ(nlog₂3) ≈ Θ(n1.585) - Master Theorem Case 1 (many small subproblems dominate), unlike the last example's Case 2.
✓
ConclusionT(n) = 3T(n/2) + n solves to T(n) = Θ(nlog₂3).
💡
Key takeawayWhen per-level cost grows instead of staying flat, the leaves - not the top - dominate the sum.
A First Look: the Master Theorem
Intuition only today - the real conditions and proof wait for Week 9.
For , compare against :
Case
When
Intuition
Result
1
grows slower
the many small subproblems (leaves) dominate
2
grows about the same
every level costs about the same
3
grows faster
the split itself dominates
Merge sort () lands in Case 2 - matching
the recursion-tree result exactly.
() lands in Case 1, since grows
slower than - matching the tree above too.
Master Theorem · worked example
Two More Recurrences, Classified
Same table as above, applied cold to two new recurrences.
GoalClassify each recurrence's case, then read off its closed form.
1
T(n) = 4T(n/2) + n²
nlog₂4 = n². f(n) = n² grows about the same → Case 2: T(n) = Θ(n² log n).
2
T(n) = T(n/2) + 1
nlog₂1 = n⁰ = 1. f(n) = 1 grows about the same → Case 2: T(n) = Θ(log n) - binary search's cost, previewed for Week 7.
★
Same signature as merge sort
Both land in Case 2, the same case as T(n) = 2T(n/2) + O(n) above - every level costing about the same is the recurring signature of Case 2.
✓
ConclusionBoth recurrences classify as Case 2, giving Θ(n² log n) and Θ(log n) respectively.
💡
Key takeawayClassifying a recurrence is a three-way comparison: does f(n) grow slower than, the same as, or faster than nlog_b a?
CampusNav: The Multi-Stop Tour, Recursively
Back to the intern's feature. Now let's actually measure it.
"Visit the library, then the gym, then a friend's dorm":
Total time = the first leg, plus the recursive time for the rest - a base case (no stops left) and a recursive case, exactly as defined a few slides ago.
Its recurrence is - the exact same shape as factorial. This part of the feature is cheap and well-behaved.
CampusNav · the feature that froze
Counting All Tour Orders - the Trap
"Show me every possible order" branches at every remaining stop.
GoalShow why this feature explodes, when `tourTime` above didn't.
1
The formula
allOrders(remaining) = sum, over every next stop in remaining, of allOrders(remaining minus next stop). allOrders(∅) = 1.
→
2
3 stops
The recursion tree branches 3 → 2 → 1, giving 3! = 6 leaves - the demo's 6 orders.
★
Why it explodes
Each extra stop multiplies, not adds, to the tree. `allOrders` is slow because it genuinely branches into more distinct choices at every level - there is no repeated work to eliminate, only an unavoidably large number of true orderings.
✓
ConclusionThe recursion itself isn't the problem - `tourTime` above was just as recursive and stayed cheap. `allOrders` explodes because it branches into every remaining stop at every level.
💡
Key takeawayWeek 11's Dynamic Programming stops re-deriving the same partial answers - but that fix only helps when answers actually repeat, which is exactly what the next example checks.
The fib(5) Call Tree
Naive recursive `fib(n) = fib(n-1) + fib(n-2)`, drawn out - a different disease from `allOrders`.
Same tree as the last slide. Now count the repeats, and compare to `allOrders`.
GoalShow that "slow and recursive" is not one disease - and that only one of the two responds to the same cure.
1
Count the repeats
`fib(3)` computed twice, `fib(2)` three times, `fib(1)` five times - 15 total calls to answer one number a loop reaches in 5 additions.
→
2
A different disease than `allOrders`
Nothing here branches into ever-more choices - the same two smaller subproblems just get asked for, over and over. Week 11 names this overlapping subproblems.
★
Would an iterative rewrite fix it?
Yes for `fib` - storing each `fib(k)` once turns 15 calls into 6, an O(n) pass (exactly Week 11's dynamic programming). No for `allOrders` - there is no repeated subproblem to cache; every one of the n! orderings is genuinely distinct, so an iterative rewrite still does n! work.
✓
Conclusion`allOrders` and naive `fib` are both exponential-ish, but for structurally different reasons - branching vs. redundant recomputation.
💡
Key takeawayDiagnosing which disease you have determines whether memoization (Week 11) can even help.
Common Mistakes
"Recursion is always less efficient than iteration." Tempting because every recursive call has function-call overhead - but the real cost driver is how many calls happen and whether they repeat work. factorial and tourTime are just as cheap, , as their iterative twins; allOrders is expensive because of its branching shape, not because it recurses.
"The base case is just where you stop." Tempting because it feels like a technicality. It is actually what bounds the entire recursion tree's depth (and, once a method branches, its size) - miss it, or shrink the wrong thing, and the tree never stops growing.
Key Words Today
Divide-and-conquer: split a problem in half, solve each half recursively, combine - previewed today, formalized Week 9.
Memoization: storing a recursive call's answer so it's never recomputed - the fix allOrders is missing, coming Week 11.
Stack overflow: a crash caused by too many "waiting" call-stack frames at once - recursion's real-world failure mode.
Closed-form solution: a formula for with no recurrence left in it - what substitution and the recursion tree both produce.
Recursion Shows Up Everywhere
CampusNav is one example. This shape is everywhere.
File system folders
Nested JSON / HTML
Tree & graph traversal
Divide-and-conquer
Backtracking search
Parsing expressions
Any structure that contains smaller versions of itself - a folder
containing folders, a sentence containing clauses, a tree containing
subtrees - is naturally described recursively.
Why This Also Matters Beyond CampusNav
Security-relevant, not just academic: real parsers
and interpreters have crashed in production from deeply nested or
adversarially crafted input hitting an unbounded recursive case -
attackers have used this deliberately. Knowing that a base case bounds
depth is not a technicality; it's a correctness and safety property.
Every advanced course after this one - compilers, databases, systems -
assumes you can look at a self-referential structure and reason
about it without flinching.
What Today's Toolkit Cannot Do
We can now trace a recursive call stack frame by frame, write down
the recurrence that describes its cost, and solve that recurrence
with substitution, a recursion tree, or an intuitive read of the
Master Theorem. But none of that gives CampusNav a fast
algorithm - right now, "find a room" and "put the directory in order"
still mean scanning an unsorted list and hoping. We have a real
toolkit for measuring cost, but still just an unsorted array and
brute force for actually reducing it.
Next Week
Week 4 leaves CampusNav with an unsorted room directory and nothing
but brute-force scans to search it. Week 5, Basic Sorting,
addresses it: the first real algorithms for putting that directory in
order, traced and proven correct by hand.
Where This Week Lives in CLRS
This week's ideas, mapped to the textbook.
This week's topic
CLRS 4th ed
Substitution method
§4.3
Recursion-tree method
§4.4
Master method
§4.5
If you want to go deeper: §4.6-4.7 cover the continuous Master
theorem and Akra-Bazzi recurrences, for shapes that don't fit the
standard Master method - useful once you meet a recurrence that
doesn't cleanly match one of today's three cases. (§4.1-4.2, matrix
multiplication and Strassen's algorithm, are not this week's
reading - they return in Week 9.)
Summary
A recursive algorithm is defined by a base case (where it stops) and a recursive case (where it calls itself on something smaller) - miss the base case and the recursion never stops.
Tracing factorial(4)'s call stack shows exactly what's "waiting" at each depth, and why the base case bounds that depth.
A recursive algorithm's cost is a recurrence relation; substitution (guess + prove by induction) and the recursion tree (sum level by level) both solve one, and the Master Theorem previews a shortcut for the divide-and-conquer shape (full rigor Week 9).
Recursion itself isn't slow - tourTime and factorial are both ; allOrders explodes from branching, not recursion, and that is exactly what Week 11's DP will fix.
Summary, Continued
New: Week 4 Check - a short graded exercise on call-stack tracing, recurrences, and the recursion-tree method, released now, due before Week 5 begins (see materials/assignments/week04-check.html).
Reading: CLRS 4th ed, §4.3-4.5 - no exercises due.
Prepare: think about how you'd put a shuffled stack of 10 index cards in order by hand. Bring your method to Week 5.
Thank You
SLOT 1: Title
notes: Open with an everyday example of explaining a rule by using the rule itself (e.g. "ask your older sibling, and if they don't know, ask THEIR older sibling"). That self-reference is today's whole topic, long before we call it "recursion."
SLOT 2: Where we are
notes: Point at Week 4. Say: "Last week gave us a ruler for growth rates. This week, we point that ruler at algorithms that call themselves."
REWRITTEN: was a discussion warm-up; now teacher-delivered narration that resolves directly
SLOT 3: Recap + open wound
NEW: Key Words Today, session 1
notes: Read each term aloud once. Say these four words are today's whole vocabulary, formalized properly in a few minutes.
SLOT 4: The pain (Act 1 / MOTIVATE), zero jargon
notes: Do not say "recursion," "recurrence," or "exponential" yet. Let the class feel the freeze first.
notes: Pause after the third bar. Say: "This is not a bug - it is structural."
SLOT 5: Cost of not knowing, split: the app-level cost here, the industry angle next
NEW: continuation - the industry angle, split out of the same slide
SLOT 6: Driving question
SLOT 7: Learning outcomes
SLOT 8: Origin, split into two
NEW: continuation of Origin
NEW: continuation - the expansion trace, split out of the same slide
SLOT 9: Core concept
NEW: continuation of the core concept, split out of the same slide
NEW: Key Words Today, session 2
notes: Read each term aloud. Say these four words return, formalized further, later this session and in Week 9.
Act 3 / BUILD: recursion vs. iteration
NEW: dense worked example, factorial(4) call-stack trace. Merges the old "Going Down" + "Going Up" slides, folds the "frames waiting" Check Yourself content.
MERGED: idea+pseudocode and the condensed trace onto one slide
Act 3 / BUILD: recurrence relations
NEW: continuation - the divide-in-half shape, split out of the same slide
NEW: induction primer, before the substitution method
NEW: dense worked example, substitution method, moderate tier
NEW: dense worked example, substitution method, harder tier. Reuses the deck's exact existing Check-Yourself recurrence.
NEW: dense worked example, recursion-tree method, moderate tier (Master Theorem Case 2 shape)
NEW: dense worked example, recursion-tree method, harder tier (Master Theorem Case 1 shape)
NEW: dense worked example, applying the Master Theorem. Folds the old Check Yourself pair, reusing its exact recurrences.
Act 3 / BUILD: CampusNav worked example, part 1
SLOT N-2: Worked example. Dense conversion of the feature that actually froze.
NEW: naive Fibonacci call tree, makes "re-deriving the same partial answers" concrete
NEW: dense worked example, the waste counted. Folds the old Check Yourself "Two Different Diseases" pair.
SLOT N-1: Common mistakes, merged into one slide
NEW: Key Words Today, session 3
notes: Read each term aloud. Say: "Memoization is the one word to remember - it's exactly what Week 11 adds to fix today's exploding tree."