easyDynamic ProgrammingMathDynamic Programming

Climbing Stairs

easyTime: O(n)Space: O(1)

The shape of the problem

You can climb 1 or 2 stairs at a time. How many distinct ways can you reach step n?

Signals to notice

count of waysstep 1 or 2recurrence on last move

Brute force first

Recurse `f(n) = f(n-1) + f(n-2)` without memoization. Exponential because it recomputes `f(k)` over and over.

The key insight

Every way to reach step n ends with either a 1-step from n-1 or a 2-step from n-2. Those two sets of paths are disjoint and cover all cases, so `f(n) = f(n-1) + f(n-2)`. It is the Fibonacci recurrence with base `f(1)=1, f(2)=2`.

Trace it on n=5

a=1 b=2                    (f(1)=1, f(2)=2)
i=3 c=a+b=3  → a=2 b=3
i=4 c=a+b=5  → a=3 b=5
i=5 c=a+b=8  → a=5 b=8
return b=8

What must stay true

After computing step i, `a` holds `f(i-1)` and `b` holds `f(i)`. Everything earlier than a has been discarded because it is no longer reachable in one more step.

Shape of the loop

if n <= 2: return n
a, b = 1, 2
for i in 3..n:
  a, b = b, a + b
return b

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Off-by-one at the base case. Using `f(1)=1, f(2)=1` gives the classic Fibonacci sequence, but this problem has `f(2)=2` (two ways: 1+1 or 2).

Dynamic Programming Pattern