← Practice
πŸ“– Dynamic programmingLearning path
Browsing as guestΒ·Sign in or create a free account to save progress and use tutor tools.
LessonΒ·difficulty 3/5Β·~18 min

DP: climbing stairs

You're climbing a staircase with n steps. Each move you take either 1 step or 2 steps. How many distinct ways can you reach the top?

The trick to dynamic programming is to notice that a big problem is made of smaller versions of itself. To land on step n, your last move came either from step n - 1 (a single step) or from step n - 2 (a double step). So:

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

That's the Fibonacci recurrence! Instead of recursing (which recomputes the same values over and over), build the answers bottom-up and keep only the last two:

text
keep two running totals (ways to reach the previous two steps)
both start at 1
roll them forward n times: each roll slides the window up one step
the answer is the total you land on

Your task

Write climb_stairs(n) that returns the number of distinct ways to climb n steps. There is exactly one way to climb 0 steps (do nothing).

python
climb_stairs(0)   # 1
climb_stairs(2)   # 2   -> (1+1), (2)
climb_stairs(3)   # 3   -> (1+1+1), (1+2), (2+1)
climb_stairs(5)   # 8

Hint: keep two running totals for "ways to reach the previous step" and "ways to reach the step before that," and roll them forward n times.

Tests

  • zero steps
  • two steps
  • three steps
  • five steps

✦ Stuck? Ask for a spark

Sign in or create a free account to use your monthly AI explainer allowance.

warming up
Loading editor…
Consolewaiting

$ Console output will appear here.

>_AI coach
Sign in or create a free account to chat with the tutor.