Recursion & Dynamic Programming, Part 1: The Idea
After this lesson, you will be able to:
- Explain how the call stack runs recursive calls, using last in, first out
- Identify base cases and recursive cases in any recursive problem
- Explain why naive Fibonacci is exponential, by counting the repeated calls
- Apply memoization (top-down DP) to eliminate redundant computation
- Build a bottom-up table with the five DP questions
- Choose between memoization and tabulation from the problem's constraints
Before you start
#Recursion: Functions Calling Themselves
- Base case. The simplest input where you can return immediately without recursing
- Recursive case. How you reduce a larger input to a smaller one and combine results
Pick the factorial preset and press play. Each call adds a frame to the top. When the base case returns, the frames are removed one at a time, newest first. The number you see at the deepest point is how much memory the recursion needs.
factorial(n) needs space for n frames at once, which is O(n) space.Step through a recursive function one call at a time. Each call adds a branch. The tree grows on the way down and closes up on the way back, the same order the call stack follows.
# The calls for factorial(4), newest on top of the stack:
#
# factorial(4) <-- frame 4: waiting for factorial(3)
# factorial(3) <-- frame 3: waiting for factorial(2)
# factorial(2) <-- frame 2: waiting for factorial(1)
# factorial(1) <-- frame 1: BASE CASE returns 1
# factorial(2) = 2 * 1 = 2 <-- frame 2 resumes, returns 2
# factorial(3) = 3 * 2 = 6 <-- frame 3 resumes, returns 6
# factorial(4) = 4 * 6 = 24 <-- frame 4 resumes, returns 24
def factorial(n: int) -> int:
"""Compute n! recursively.
Time: O(n), n recursive calls.
Space: O(n), n frames on the call stack at the same time.
"""
if n <= 1: # BASE CASE: stop recursing
return 1
return n * factorial(n - 1) # RECURSIVE CASE: reduce to smaller problem
print(factorial(4)) # 24
print(factorial(10)) # 3628800RecursionError, which protects you from a base case that never fires.import sys
print(sys.getrecursionlimit()) # 1000
# You can raise the limit, but prefer a loop for very deep recursion.
# We put the old value back at once so later cells keep the default.
old_limit = sys.getrecursionlimit()
sys.setrecursionlimit(10000)
print(sys.getrecursionlimit()) # 10000
sys.setrecursionlimit(old_limit)HitRecursionError: maximum recursion depth exceeded? Either your base case never fires (infinite recursion — check the condition) or the problem genuinely needs more than 1000 frames (use iteration orsys.setrecursionlimit). See the error decoder for the diagnosis flow.
#Classic Recursion Examples
Recursive functions come in a few shapes. Below, each shape has a trace by hand first, then the code. Read the trace, guess what the function returns, then look at the code.
#Shape 1: one smaller call
factorial above is the first shape: one call on a smaller input. Here is another. To add up a list, take the first value and add the sum of the rest. Trace sum_list([1, 2, 3]) by hand:sum_list([1, 2, 3])
= 1 + sum_list([2, 3])
= 1 + (2 + sum_list([3]))
= 1 + (2 + (3 + sum_list([]))) <- empty list: the base case, returns 0
= 1 + (2 + (3 + 0))
= 6
lst[1:] is a copy of the list without its first value. Copying takes n steps on every call, so this version is O(n²). Passing an index instead of a slice makes it O(n).def sum_list(lst: list[int]) -> int:
if not lst: # base case: empty list
return 0
return lst[0] + sum_list(lst[1:]) # first value + sum of the rest
print(sum_list([1, 2, 3, 4, 5])) # 15#Shape 2: two smaller calls
fib_naive function the whole lesson reuses.# Naive Fibonacci: O(2^n) time, O(n) space.
# It is slow on purpose. Memoization below fixes it.
def fib_naive(n: int) -> int:
if n <= 1:
return n
return fib_naive(n - 1) + fib_naive(n - 2)
print([fib_naive(i) for i in range(8)]) # [0, 1, 1, 2, 3, 5, 8, 13]#Shape 3: halve the problem
Throw away half of the work on every call and the number of calls drops to O(log n). Fast power uses the fact that x^8 = (x^4)^2. Binary search (the algorithms-basics lesson covers it in full) looks at the middle of a sorted list and keeps only the half that can hold the target.
def power(base: float, exp: int) -> float:
"""Compute base^exp in O(log exp) using recursive squaring."""
if exp == 0:
return 1
if exp % 2 == 0:
half = power(base, exp // 2)
return half * half # x^8 = (x^4)^2: square the result
return base * power(base, exp - 1)
print(power(2, 10)) # 1024
print(power(3, 5)) # 243
def binary_search(arr: list[int], target: int,
lo: int = 0, hi: int | None = None) -> int:
"""Return the index of target or -1 if not found."""
if hi is None:
hi = len(arr) - 1
if lo > hi:
return -1 # base case: nothing left to search
mid = (lo + hi) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
return binary_search(arr, target, mid + 1, hi) # right half
else:
return binary_search(arr, target, lo, mid - 1) # left half
print(binary_search([1, 3, 5, 7, 9, 11], 7)) # 3
print(binary_search([1, 3, 5, 7, 9, 11], 4)) # -1#Shape 4: split, solve both halves, join
Merge sort cuts a list in two, sorts each half by calling itself, and merges the two sorted halves into one.
def merge_sort(arr: list[int]) -> list[int]:
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return _merge(left, right)
def _merge(left: list[int], right: list[int]) -> list[int]:
result, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i]); i += 1
else:
result.append(right[j]); j += 1
return result + left[i:] + right[j:]
print(merge_sort([5, 2, 8, 1, 9, 3])) # [1, 2, 3, 5, 8, 9]#Going further: nested data and choose-then-undo
flatten calls itself on every list it finds inside a list, however deep. permutations makes a choice, recurses, then undoes the choice to try the next one. Undoing a choice to try another is called backtracking.def flatten(nested) -> list:
"""Recursively flatten a list of any nesting depth.
flatten([1, [2, [3, 4]], 5]) -> [1, 2, 3, 4, 5]
"""
result = []
for item in nested:
if isinstance(item, list):
result.extend(flatten(item)) # recurse into sublist
else:
result.append(item)
return result
print(flatten([1, [2, [3, [4]], 5], 6])) # [1, 2, 3, 4, 5, 6]
def permutations(lst: list) -> list[list]:
"""Generate all permutations of a list.
Strategy: for each element, make it the first element,
then recursively permute the rest.
"""
if len(lst) <= 1:
return [lst[:]] # base case: one permutation of 0 or 1 elements
result = []
for i in range(len(lst)):
lst[0], lst[i] = lst[i], lst[0] # choose element i as first
for perm in permutations(lst[1:]):
result.append([lst[0]] + perm) # prepend chosen element
lst[0], lst[i] = lst[i], lst[0] # restore (backtrack)
return result
perms = permutations([1, 2, 3])
print(f"{len(perms)} permutations:", perms)
# 6 permutations: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,2,1],[3,1,2]]fib(4) — watch the call tree expand and collapse
Step through the recursive calls and returns to watch the call tree grow, results fill in, and the call stack change.
A recursion call tree for the supplied function, shown above its source code with a call stack panel beside it. It starts at step 0 with an empty tree and empty stack; each step adds a call or fills in a return value, until the tree is complete.
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)#See the call stack itself, frame by frame
fib(...) or factorial(...) call adds a stack frame with its own variables, and each return removes the top frame. Last in, first out. The animation below also has a factorial(4) preset and an exception preset. When an error is raised, frames are removed without giving back a value.#Now trace it yourself
factorial(n - 1) call. Then watch it shrink as each frame hands its product back.Edit the code, then click Trace it. Python actually runs in your browser — every line, every variable, every print.
Click Trace it to capture the execution trace. The scrubber below will let you step through every variable change line-by-line.
#The Problem with Naive Recursion
fib_naive(5), the function defined in Shape 2 above: fib(5)
/ \
fib(4) fib(3)
/ \ / \
fib(3) fib(2) fib(2) fib(1)
/ \ / \ / \
fib(2) fib(1) fib(1) fib(0) fib(1) fib(0)
/ \
fib(1) fib(0)
fib(2) is called: 3 times. fib(3) is called 2 times. For fib(40), fib(2) is called millions of times. The same values are worked out again and again.# Count the calls to see the explosion. This is fib_naive with a counter added.
call_count = 0
def fib_counted(n: int) -> int:
global call_count
call_count += 1
if n <= 1:
return n
return fib_counted(n - 1) + fib_counted(n - 2)
for n in [10, 20, 30, 35]:
call_count = 0
result = fib_counted(n)
print(f"fib({n:>2}) = {result:>10,} | calls: {call_count:>12,}")
# fib(10) = 55 | calls: 177
# fib(20) = 6,765 | calls: 21,891
# fib(30) = 832,040 | calls: 2,692,537
# fib(35) = 9,227,465 | calls: 29,860,703
# At n=50 this would take minutes. At n=100 it would not finish in your lifetime.
# The call count is calls(n) = 2 * fib(n+1) - 1, which grows like 1.618^n.fib_naive(40) makes about how many function calls?
#Memoization: Top-Down Dynamic Programming
import functools
# fib_naive is the function defined in Shape 2. We reuse it for the timing
# comparison at the end.
# --- Method 1: @functools.lru_cache, the cleanest way ---
@functools.lru_cache(maxsize=None) # None = unlimited cache size
def fib_memo(n: int) -> int:
"""Memoized fibonacci. Time: O(n), Space: O(n).
lru_cache watches each call. If fib_memo(k) was computed before,
it returns the stored value at once. Each n is computed only once.
"""
if n <= 1:
return n
return fib_memo(n - 1) + fib_memo(n - 2)
# With memoization, fib(n) computes only n+1 different values, not 2^n calls
print(fib_memo(50)) # 12586269025 (instant!)
print(fib_memo(100)) # 354224848179261915075 (still instant)
# Inspect the cache
print(fib_memo.cache_info())
# CacheInfo(hits=99, misses=101, maxsize=None, currsize=101)
# Only 101 unique calls made for fib(100)!
# --- Method 2: Manual memo dict ---
def fib_manual_memo(n: int, memo: dict | None = None) -> int:
"""Memoized fibonacci with explicit dictionary."""
if memo is None:
memo = {}
if n in memo:
return memo[n] # cache hit: return stored result
if n <= 1:
return n
memo[n] = fib_manual_memo(n - 1, memo) + fib_manual_memo(n - 2, memo)
return memo[n] # store before returning
print(fib_manual_memo(100)) # 354224848179261915075
# --- Method 3: functools.cache (Python 3.9+, shorthand for lru_cache(maxsize=None)) ---
@functools.cache
def fib_cache(n: int) -> int:
if n <= 1:
return n
return fib_cache(n - 1) + fib_cache(n - 2)
# Performance comparison
import time
def benchmark(label, fn, n, repeat=1):
# One cached call is too fast to time, so repeat it and take the average.
start = time.perf_counter()
for _ in range(repeat):
result = fn(n)
elapsed_ms = (time.perf_counter() - start) / repeat * 1000
print(f"{label}: fib({n}) = {result} in {elapsed_ms:.5f} ms per call")
benchmark("Naive (n=35)", fib_naive, 35) # about 1000 to a few thousand ms (machine dependent)
benchmark("Memo (n=35)", fib_memo, 35, 100_000) # well under 0.01 ms
benchmark("Memo (n=100)", fib_memo, 100, 100_000) # well under 0.01 ms#Tabulation: Bottom-Up Dynamic Programming
Which one should you pick? Memoization is easiest to write from the rule. It only computes the answers it needs. Tabulation is faster per step and never hits the recursion limit. Part 2 comes back to the choice with real problems.
# --- Fibonacci: bottom-up tabulation ---
def fib_table(n: int) -> int:
"""Fibonacci via tabulation. Time: O(n), Space: O(n)."""
if n <= 1:
return n
dp = [0] * (n + 1)
dp[0] = 0 # base case
dp[1] = 1 # base case
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2] # the rule: this answer from smaller ones
return dp[n]
print(fib_table(10)) # 55
print(fib_table(50)) # 12586269025
# --- Less memory: O(1) space (a "rolling" pair of variables) ---
# dp[i] only needs dp[i-1] and dp[i-2].
# So we keep just the last two values, not the whole table.
def fib_optimized(n: int) -> int:
"""Fibonacci with O(1) space using rolling variables."""
if n <= 1:
return n
prev2, prev1 = 0, 1
for _ in range(2, n + 1):
curr = prev1 + prev2
prev2, prev1 = prev1, curr
return prev1
print(fib_optimized(100)) # 354224848179261915075
print(fib_optimized(1000)) # a very large number, computed in microseconds
# --- Show the table for small n ---
def fib_table_verbose(n: int) -> int:
"""Same as fib_table but prints the table."""
dp = [0] * (n + 1)
dp[1] = 1
print(f"Index: {list(range(n+1))}")
print(f"Init: {dp}")
for i in range(2, n + 1):
dp[i] = dp[i-1] + dp[i-2]
print(f"Final: {dp}")
return dp[n]
fib_table_verbose(8)
# Index: [0, 1, 2, 3, 4, 5, 6, 7, 8]
# Init: [0, 1, 0, 0, 0, 0, 0, 0, 0]
# Final: [0, 1, 1, 2, 3, 5, 8, 13, 21]#The DP Framework
# THE 5-QUESTION DP FRAMEWORK
# ================================================
# 1. WHAT IS THE STATE?
# Which numbers say exactly which sub-problem I am on?
# → dp[i] = ? (or dp[i][j] for 2D problems)
#
# 2. WHAT IS THE RECURRENCE?
# How is dp[i] built from smaller answers dp[i-1], dp[i-2], etc.?
# → dp[i] = some function of dp[i-1], dp[i-2], ...
#
# 3. WHAT ARE THE BASE CASES?
# What are the smallest subproblems I can answer directly?
# → dp[0] = ?, dp[1] = ?
#
# 4. WHAT ORDER DO I FILL THE TABLE?
# Left to right? Right to left? Row by row?
# → dp[i] must be computed after all subproblems it depends on
#
# 5. WHAT IS THE FINAL ANSWER?
# Is it dp[n]? max(dp)? dp[-1][-1]?
# → depends on the problem
# ---- EXAMPLE: Climbing Stairs ----
# Problem: n steps. Each move: climb 1 or 2 steps. How many distinct ways?
#
# 1. STATE: dp[i] = number of distinct ways to reach step i
# 2. RECURRENCE: dp[i] = dp[i-1] + dp[i-2]
# (arrive from step i-1 with a 1-step move, or from step i-2 with a 2-step move)
# 3. BASE CASES: dp[0] = 1 (one way to stay on the ground), dp[1] = 1 (one way to reach step 1)
# 4. ORDER: left to right, i from 2 to n
# 5. ANSWER: dp[n]
def climb_stairs(n: int) -> int:
"""Count distinct ways to climb n stairs (1 or 2 steps at a time)."""
if n <= 2:
return n
dp = [0] * (n + 1)
dp[0] = 1 # base case: 1 way to be at the start
dp[1] = 1 # base case: 1 way to reach step 1
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
for stairs in range(1, 8):
print(f"climb_stairs({stairs}) = {climb_stairs(stairs)}")
# 1, 2, 3, 5, 8, 13, 21 -- the Fibonacci sequence!What does memoization actually do for a recursive function like fib(n)?
#Interactive Visualization: Recursion Tree & Memoization
Watch recursion trees expand in real time. Toggle memoization on/off to see how it prunes redundant branches and compare naive vs DP performance:
#Code Playground: The Same Problem, Three Ways
n stairs taking 1 or 2 at a time — written naively, memoized, and tabulated, with a counter that shows exactly how much work each one does.#Key Takeaways
- Every recursive function needs a base case and a recursive case. The base case stops the recursion. The recursive case makes the problem smaller. Without a base case the calls never stop.
- Naive recursion that repeats sub-problems is slow.
fib(n)recomputes the same values, which grows like 2^n. One line,@functools.cache, makes it O(n). - Memoization is recursion plus a cache. Tabulation is a loop that fills a table. They cost about the same. Memoization is easier to write from the rule. Tabulation has no call overhead and cannot overflow the stack.
- Answer the five DP questions before you write code: the state, the recurrence, the base cases, the fill order and the final answer.
- DP needs two things. Overlapping sub-problems make caching worth it. Optimal substructure means the best answer to the whole is built from the best answers to the parts.
- Python's recursion limit is about 1000 frames and it is a real ceiling. A recursion over 10,000 items raises RecursionError, so a loop-based table is often the better choice.
What is the time complexity of the naive recursive Fibonacci implementation fib(n) = fib(n-1) + fib(n-2)?