AlgoViz

Climbing stairs

easy 15 min

Climbing stairs asks how many different sequences of 1-steps and 2-steps reach stair n.

Video lesson · Chapter 1 of 5

Count the last landing

0:00 / 4:13

Climbing stairs in 75 seconds

1:22Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Look at the last move. Stair n was reached by a 1-step from n - 1 or a 2-step from n - 2, never both

Understand it

Start here

The problem

A staircase has nn stairs. Each move climbs either 1 stair or 2 stairs. In how many distinct ways can you reach the top exactly? Two ways are different if the sequence of moves differs, so 1+2 and 2+1 count separately. This is LeetCode 70 and the usual first problem in dynamic programming.

Stairs nWaysThe sequences
111
221+1, 2
331+1+1, 1+2, 2+1
451+1+1+1, 1+1+2, 1+2+1, 2+1+1, 2+2
58eight sequences, from 1+1+1+1+1 to 2+2+1
1, 2, 3, 5, 8: each count is the sum of the two above it. That is the whole problem in one column.
  • A single array of states

    In 1D DP each stair ii is one state, stored in one cell dp[i], and the cells are filled in one direction.

  • Dependencies sit behind you

    dp[i] only reads dp[i - 1] and dp[i - 2], like a line of dominoes where each one is pushed by the two before it.

  • Same family

    Fibonacci, house robber, min cost climbing and maximum subarray are all 1D DP over a line of states.

The key insight

Think about the last move

Do not try to plan the whole climb. Look only at the final move onto stair nn. It was a 1-step from stair n−1n - 1 or a 2-step from stair n−2n - 2. Every way to reach n−1n - 1 extends to nn in one way, and so does every way to reach n−2n - 2.

Where the last move came from

The two groups never overlap (the last moves differ) and together they cover every sequence, so the counts simply add.

The recurrence

ways(n)=ways(n−1)⏟last move +1+ways(n−2)⏟last move +2,n≥2\text{ways}(n) = \underbrace{\text{ways}(n-1)}_{\text{last move } +1} + \underbrace{\text{ways}(n-2)}_{\text{last move } +2}, \qquad n \ge 2
Check with n=4n = 4: the 3 paths to stair 3 each get +1, the 2 paths to stair 2 each get +2, total 3+2=53 + 2 = 5.

Base cases

Why ways(0) = 1

The full definition

ways(n)={1n=01n=1ways(n−1)+ways(n−2)n≥2\text{ways}(n) = \begin{cases} 1 & n = 0 \\ 1 & n = 1 \\ \text{ways}(n-1) + \text{ways}(n-2) & n \ge 2 \end{cases}
Two base cases, because the rule reaches two stairs back.
  • ways(0) = 1

    Zero stairs to climb: you are already there, and doing nothing is one way. It is the empty path every real path starts from. With 0 here, dp[2] would be 1 instead of 2.

  • ways(1) = 1

    One stair: a single 1-step. A 2-step would overshoot, so there is no other option.

  • Or start at 1 and 2

    Many solutions skip stair 0 and use ways(1) = 1, ways(2) = 2. Same sequence, same answers for every n≥1n \ge 1.

Approach 1

Brute recursion and its call tree

Python
def ways(n):    if n <= 1:                 # ways(0) = ways(1) = 1        return 1    return ways(n - 1) + ways(n - 2)for n in range(1, 9):    print(n, ways(n))          # 1 1, 2 2, 3 3, 4 5, 5 8, 6 13, 7 21, 8 34
The recurrence, typed in directly. Correct, but slow.
Edit and run it in your browser

Call tree of ways(5)

15 calls for 6 distinct questions. Everything in red repeats work done elsewhere in the tree.
CallTimes made inside ways(5)
ways(5)1
ways(4)1
ways(3)2
ways(2)3
ways(1)5
ways(0)3
The repeat counts are Fibonacci numbers too: the waste grows at the same rate as the answer.

Complexity

Why brute force is exponential

Count the calls

C(n)=C(n−1)+C(n−2)+1,C(0)=C(1)=1⟹C(n)=2 ways(n)−1C(n) = C(n-1) + C(n-2) + 1,\quad C(0) = C(1) = 1 \quad\Longrightarrow\quad C(n) = 2\,\text{ways}(n) - 1
Check: C(5)=2⋅8−1=15C(5) = 2 \cdot 8 - 1 = 15, C(20)=2⋅10946−1=21,891C(20) = 2 \cdot 10946 - 1 = 21{,}891, and C(45)≈3.67C(45) \approx 3.67 billion.

How fast ways(n) grows

ways(n)≈c xn  ⇒  x2=x+1  ⇒  x=φ=1+52≈1.618⟹T(n)=Θ(φn)⊂O(2n)\text{ways}(n) \approx c\,x^n \;\Rightarrow\; x^2 = x + 1 \;\Rightarrow\; x = \varphi = \frac{1+\sqrt5}{2} \approx 1.618 \quad\Longrightarrow\quad T(n) = \Theta(\varphi^n) \subset O(2^n)
Each extra stair multiplies the work by about 1.618. Quoting O(2n)O(2^n) is a correct upper bound.

Space is only O(n)O(n): a branch finishes and is popped before its sibling starts, so the call stack holds one root-to-leaf path at a time, at most nn frames.

Approach 2

Memoisation: top-down DP

One memoised call

Each stair reaches the bottom box once. For n=5n = 5 that is 9 calls instead of 15; in general 2n−12n - 1 calls, O(n)O(n) time.
Python
from functools import cachedef ways_memo(n, memo=None):    if memo is None:        memo = {}                  # never memo={} in the signature    if n in memo:        return memo[n]    if n <= 1:        return 1    memo[n] = ways_memo(n - 1, memo) + ways_memo(n - 2, memo)    return memo[n]@cachedef ways_cached(n):    return 1 if n <= 1 else ways_cached(n - 1) + ways_cached(n - 2)print(ways_memo(45), ways_cached(90))   # 1836311903 4660046610375530309
A dictionary memo, and the same thing with the standard library.
Edit and run it in your browser

Approach 3

Tabulation: a 1D dp array

i012345
dp[i]112358
howbasebase1 + 12 + 13 + 25 + 3
Filled left to right for n=5n = 5. Each cell reads the two cells before it, which are always ready.

The bottom-up loop

No recursion and no stack: n−1n - 1 additions, O(n)O(n) time and O(n)O(n) space for the array.
Python
def ways_table(n):    if n <= 1:        return 1    dp = [0] * (n + 1)    dp[0] = dp[1] = 1    for i in range(2, n + 1):        dp[i] = dp[i - 1] + dp[i - 2]    return dp[n]print([ways_table(n) for n in (3, 5, 7)])   # [3, 8, 21]
Bottom-up with the full array, the version the visualizer steps through.
Edit and run it in your browser

Approach 4

O(1) space: keep two numbers

Only a window of two cells is ever read

dp[i]=dp[i−1]+dp[i−2]⟹(a,  b)  ←  (b,  a+b)dp[i] = dp[i-1] + dp[i-2] \quad\Longrightarrow\quad (a,\; b) \;\leftarrow\; (b,\; a + b)
Keep a=dp[i−2]a = dp[i-2] and b=dp[i−1]b = dp[i-1]; one update slides the pair up a stair.
Sliding the pair for n = 7
  1. 1a, b = 1, 2ways(1), ways(2)
  2. 2i = 32, 3
  3. 3i = 43, 5
  4. 4i = 55, 8
  5. 5i = 68, 13
  6. 6i = 713, 21: return b

Five updates and two numbers of memory give ways(7) = 21.

Python
def climb_stairs(n):    if n <= 2:        return n                   # 1 -> 1, 2 -> 2    a, b = 1, 2                    # ways(1), ways(2)    for _ in range(3, n + 1):        a, b = b, a + b            # right side is computed first    return bprint([climb_stairs(n) for n in range(1, 11)])   # [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
The interview answer: O(n)O(n) time, O(1)O(1) space.
Edit and run it in your browser

Two variables

  • O(1)O(1) extra space, whatever nn is.
  • No recursion, so no recursion limit.
  • Same O(n)O(n) time as the array.

Full dp array

  • O(n)O(n) space for values read once and then forgotten.
  • Only worth keeping if you need every count, not just the last.
  • Easy to index past the end when n=0n = 0.

The connection

It is Fibonacci, shifted by one

Same rule, different start

ways(0)=1=F(1),ways(1)=1=F(2)⟹ways(n)=F(n+1)\text{ways}(0) = 1 = F(1),\quad \text{ways}(1) = 1 = F(2) \quad\Longrightarrow\quad \text{ways}(n) = F(n+1)
Both sequences add the two previous terms, and the stairs sequence starts one place later. See Recursion: Fibonacci for the call tree in depth.
n012345678
F(n)F(n)01123581321
ways(n)112358132134
The ways row is the Fibonacci row moved one column to the left.

A closed form, and why not to use it

ways(n)=F(n+1)=φ n+1−ψ n+15,ψ=1−52≈−0.618\text{ways}(n) = F(n+1) = \frac{\varphi^{\,n+1} - \psi^{\,n+1}}{\sqrt5}, \qquad \psi = \frac{1-\sqrt5}{2} \approx -0.618
Binet's formula is exact on paper, but floating-point rounding makes it wrong past about n=70n = 70.

Generalise

1 to k steps, step sets and costs

Any set of allowed step sizes S

ways(n)=∑s∈S,  s≤nways(n−s),ways(0)=1\text{ways}(n) = \sum_{s \in S,\; s \le n} \text{ways}(n - s), \qquad \text{ways}(0) = 1
S={1,2}S = \{1, 2\} is the classic problem. S={1,2,3}S = \{1, 2, 3\} gives ways(n)=ways(n−1)+ways(n−2)+ways(n−3)\text{ways}(n) = \text{ways}(n-1) + \text{ways}(n-2) + \text{ways}(n-3), the Tribonacci numbers. For S={1,…,k}S = \{1, \dots, k\} keep a running sum of the last kk cells to stay O(n)O(n).
Steps allowedn = 123456
{1}111111
{1, 2}1235813
{1, 2, 3}12471324
{1, 3}112346
Each row follows the sum rule with its own set of sizes.

Cost variant: minimise instead of count

best(i)=cost(i)+min⁡(best(i−1),  best(i−2))\text{best}(i) = \text{cost}(i) + \min\big(\text{best}(i-1),\; \text{best}(i-2)\big)
Same two arrows into each stair, but you pay for stairs and keep the cheaper arrival. That is min cost climbing stairs. Counting adds; optimising takes min or max.
  • Min cost climbing

    Pay cost[i] to stand on stair ii; take the cheaper of the two ways in. Open the topic.

  • House robber

    Rob house ii plus the best up to i−2i - 2, or skip it: the same two-back shape with a max. Open the topic.

  • Decode ways

    Read one digit or two digits at a time: climbing stairs where some 1- or 2-steps are not allowed.

  • Domino tiling of 2 × n

    The last piece is one vertical domino or two horizontal ones: exactly ways(n).

Pattern spotting

Choosing an approach

From problem statement to code

For climbing stairs every branch ends at the two-variable loop.
ApproachTimeSpaceNotes
Brute recursionΘ(φn)\Theta(\varphi^n), quoted O(2n)O(2^n)O(n)O(n) stackLists every path; times out past n≈35n \approx 35
Memoisation (top-down)O(n)O(n)O(n)O(n) memo + stackKeeps the recursive shape; depth limit applies
Tabulation (bottom-up)O(n)O(n)O(n)O(n)Keeps every count
Two variablesO(n)O(n)O(1)O(1)The standard answer
Matrix powerO(log⁡n)O(\log n)O(1)O(1)Only for huge nn with a modulus
The space-optimised loop has the same time as tabulation; only the memory changes.

Recap

Key takeaways

Key points

  • Split by the last move: ways(n) = ways(n - 1) + ways(n - 2) for n ≥ 2.
  • Base cases ways(0) = 1 (the empty path) and ways(1) = 1, or equivalently ways(1) = 1 and ways(2) = 2.
  • The answers 1, 1, 2, 3, 5, 8 are Fibonacci shifted by one: ways(n) = F(n + 1).
  • Brute recursion makes 2·ways(n) - 1 calls: Θ(φⁿ) time, O(n) stack.
  • Memoisation and tabulation compute each stair once: O(n) time, O(n) space.
  • Only the last two values are read, so two variables give O(1) space.
  • With steps 1 to k, add the last k cells; with costs, take a min instead of a sum.

Sources