Lesson 1 · Unit 01
Overlapping subproblems
Why naive recursion repeats itself, and how a memo stops it
What you practise
- Repeated work in the call tree
- A memo makes it linear
Try a question from this lesson
Pick one
To work out fib(5), how many separate times does this function compute fib(2)?
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)function fib(n) {
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
}function fib(n: number): number {
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
}Correct answer
3
Why
fib(5) needs fib(4) and fib(3). fib(4) needs fib(3) again, and every fib(3) needs its own fib(2). That makes three fib(2) calls, each recomputed from scratch because nothing is remembered.
TypeScript noteA recursive function needs its return type written out (: number). TypeScript cannot infer it from a body that calls itself.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
The same question, asked again
Draw the calls as a tree. fib(3) appears twice and fib(2) three times, and each repeat redoes its whole subtree.
A recursion that keeps asking for the same inputs has overlapping subproblems. That is the signal for dynamic programming: solve each subproblem once and remember the answer.
fib(5)
├─ fib(4)
│ ├─ fib(3)
│ │ ├─ fib(2)
│ │ └─ fib(1)
│ └─ fib(2)
└─ fib(3)
├─ fib(2)
└─ fib(1)fib(5)
├─ fib(4)
│ ├─ fib(3)
│ │ ├─ fib(2)
│ │ └─ fib(1)
│ └─ fib(2)
└─ fib(3)
├─ fib(2)
└─ fib(1)fib(5)
├─ fib(4)
│ ├─ fib(3)
│ │ ├─ fib(2)
│ │ └─ fib(1)
│ └─ fib(2)
└─ fib(3)
├─ fib(2)
└─ fib(1)9 more exercises in the app
- 2× type the answer
- 3× multiple choice
- 1× fill the blanks
- 1× true or false
- 1× match the pairs
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.