We start with a story shock π¦, then learn why DP works: overlapping subproblems + optimal substructure.
Story Hook: βCompute the 400th Fibonacci termβ¦ using simple recursion.β
Naive recursion looks short and innocent β but the recursion tree explodes.
Estimated calls β 1083
Time @ 1 ns/call β 1067 years
Earthβs age is only ~ 4.5 Γ 109 years.
π¦ Started at Earthβs birthβ¦ still running today π
π¦ Started in dinosaur ageβ¦π Still not finishedβ¦β³ DP saves the day.
β DP Mode ON β now itβs fast.
See the approximation (simple + realistic)
π Naive Fibonacci recursion makes roughly:
β 1083 function calls
β‘ If each call takes 1 nanosecond (10-9 sec):
Total time β 1067 years
π Earthβs age β 4.5 Γ 109 years
π¦ If it started at Earth's birthβ¦ it would still be running today π
Key idea: same subproblems repeat πDP caches results β Time drops to O(n) for Fibonacci β‘
Still computing F(400)β¦ ETA: β
1) Overlapping Subproblems
Same subproblems appear again and again. Store once β reuse.
Cache / memo tableβSolve onceβ
2) Optimal Substructure
Optimal answer can be built from optimal answers of smaller subproblems.
Build small β bigReuse best sub-answers
Two DP Styles
Top-Down (Memoization)
Recursion + memo[]; avoids recomputation using memo hits.
Recursion + cacheMay hit recursion depth
Bottom-Up (Tabulation)
Iteratively fill dp[] from base cases to answer.
Loop + tableEasy space optimization
Interactive Demo: Fibonacci with DP
Switch modes, then Step/Auto to watch memo/dp fill.
Demo n:(β€ 40 for smooth steps)
Computed states
0
Memo hits (Top-Down)
0
Total calls
0
Result fib(n)
β
π§ Debug View (Pseudocode + Step Meaning + Call Stack + Mini Tree)
Pseudocode (auto-switches)
What this step means
Click Step to start. βMEMO HITβ means subtree skipped β
Call Stack (Top-Down)
Top of stack β
(empty)
Push on CALL, pop on RETURN.
Why it helps
Shows which calls are waiting. MEMO HIT returns immediately without growing the stack.
π³ Mini Recursion Tree (Top-Down)
Tree view limited to n β€ 8 for clarity.
(tree will appear here)
Tip: Click Run, then use Step or Auto.
DP / Memo Table
index β value
What to notice
Top-Down: memo hit β instant return (skips subtree).
Bottom-Up: dp[0..n] filled once in order.
Next in DP Module
Continue module-wise from your index placeholders: