Course outline · 0% complete

0/30 lessons0%

Course overview →

From memo to table: climbing stairs

lesson 9-1 · ~14 min · 23/30

Quiz

Warm-up from lesson 5-3: memoization made fib fast. What was the cost formula you carried out of that lesson?

Climbing stairs

The interview classic: a staircase has n steps, and you can climb 1 or 2 steps at a time. How many distinct ways can you reach the top?

Think about the last move onto step n. It came from step n-1 (a 1-step) or from step n-2 (a 2-step). Those two groups cover every way, and they cannot overlap. So:

ways(n) = ways(n-1) + ways(n-2)

with ways(1) = 1 and ways(2) = 2. That equation is called a recurrence, and it is fib from unit 5 in a costume.

You already know one way to compute it fast: recursion + memo. Dynamic programming (DP) flips the direction: instead of starting at n and recursing down, fill a table from the bottom up. table[i] holds ways(i), and by the time you compute table[i], its two ingredients are already sitting in the table.

table[i] = table[i-1] + table[i-2]12358?i=1i=2i=3i=4i=5i=6fill left to right, ingredients are always already computed
Bottom-up DP: each cell is built from earlier cells. table[5] = table[4] + table[3] = 5 + 3. No recursion, no re-computation.

Code exercise · python

Run this. Both versions compute the same recurrence: climb_memo recurses down with a memo (lesson 5-3 style), climb_table fills bottom-up with a plain loop. Same answers, and the table version cannot hit recursion limits.

The O(1)-space follow-up

The follow-up interviewers reach for first: "your table costs O(n) memory — do you actually need it?" Read the recurrence again: computing table[i] touches only table[i-1] and table[i-2]. Everything older is dead weight. So keep just two variables and slide them forward — same computation, same answer, O(1) space.

This works whenever the recurrence has a fixed, short reach back (climbing stairs, house robber, fib). It does NOT work when the recurrence can reach arbitrarily far — coin change reads table[a - c] for every coin c — so state the reach out loud before claiming the optimization.

Code exercise · python

Run this. Two variables replace the whole table: after every loop turn, a and b hold ways(i-1) and ways(i). climb(45) still answers instantly — 1,836,311,903 ways.

Code exercise · python

Your turn. Each step i has a cost. After paying cost[i] you may climb 1 or 2 steps, you may start on step 0 or step 1, and the top is one past the last step. Fill table[i] = cheapest total cost to REACH position i (so table[0] = table[1] = 0).

Quiz

What are the two ingredients you must state before writing ANY dynamic programming table?