AlgoViz

Climbing stairs

easy 15 min

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

See it run

Watch the brute-force tree redo the same stairs, then prune it with a memo, flatten it into a dp array and shrink it to two variables.

Operations

Brute recursion: ways(5)

Ask: how did the last move reach stair n? Either a 1-step from n - 1 or a 2-step from n - 2, so ways(n) = ways(n - 1) + ways(n - 2). Coded as plain recursion, each call makes two more and the same subtrees appear again and again.

Step 1 of 10

One question, split by the last move

w(5)call 1

ways(5) = ?

We want ways(5): the number of different sequences of 1-steps and 2-steps that land exactly on stair 5. Every such sequence ends with either a 1-step (from stair 4) or a 2-step (from stair 3), never both.

Step 1: One question, split by the last move

def ways(n):    if n <= 1:              # 0 steps left: 1 way (stand still); 1 step left: 1 way        return 1    one = ways(n - 1)       # last move was a 1-step, from stair n - 1    two = ways(n - 2)       # last move was a 2-step, from stair n - 2    return one + two
Time
O(2ⁿ), exactly Θ(φⁿ)
Space
O(n) call stack
ways(5)
15 calls
ways(20)
21,891 calls
ways(45)
3.67 billion calls

Draw the tree for n = 5 once and circle the repeated labels. If the same call shows up twice, a cache will pay off.

In the real world

The same climbing stairs doing real jobs. Pick one and step through it.

The climber from the original visualizer tries every sequence of 1-steps and 2-steps up a 4-stair flight, one path at a time, so you can count the 5 ways by hand before trusting the formula.

Step 1 of 8

At the bottom of 4 stairs

  1. startyou
  2. 1
  3. 2
  4. 3
  5. top
path = –paths found = 0

Each move is a 1-step or a 2-step. We list the paths in a fixed order, trying a 1-step before a 2-step at every choice, so none is missed or repeated.

Step 1: At the bottom of 4 stairs

def all_paths(n, path=()):    if n == 0:        print("+".join(map(str, path)))        return    for step in (1, 2):        if step <= n:            all_paths(n - step, path + (step,))all_paths(4)   # 1+1+1+1, 1+1+2, 1+2+1, 2+1+1, 2+2

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Setting dp[0] = 0

    critical

    dp[0] counts the empty path, which is one way to stand on stair 0. With dp[0] = 0, dp[2] = dp[1] + dp[0] = 1 instead of 2, and every later answer is wrong. If you prefer to avoid dp[0], start from dp[1] = 1 and dp[2] = 2 instead.

    Wrong
    dp[0], dp[1] = 0, 1# dp[2] = 1, dp[3] = 2 ... off by one place
    Right
    dp[0], dp[1] = 1, 1          # empty path counts as one way# dp[2] = 2, dp[3] = 3, dp[5] = 8
  • Copying Fibonacci's base cases

    major

    Fibonacci returns n for n <= 1, so fib(0) = 0. Climbing stairs needs ways(0) = 1. Pasting the Fibonacci code computes F(n) instead of F(n + 1): ways(5) comes out as 5, not 8.

    Wrong
    def ways(n):    if n <= 1:        return n               # ways(0) = 0: wrong for stairs    return ways(n - 1) + ways(n - 2)
    Right
    def ways(n):    if n <= 1:        return 1               # ways(0) = ways(1) = 1    return ways(n - 1) + ways(n - 2)
  • Updating the two variables in the wrong order

    critical

    Overwriting prev1 before saving it into prev2 loses the old value, so the sum uses the new one twice and the numbers double instead of following Fibonacci.

    Wrong
    curr = prev1 + prev2prev1 = currprev2 = prev1                # this is now curr, not the old prev1
    Right
    curr = prev1 + prev2prev2 = prev1                # save the old value firstprev1 = curr# or in one line: prev2, prev1 = prev1, prev1 + prev2
  • Plain recursion for real inputs

    major

    Brute force makes 2 · ways(n) - 1 calls: about 3.67 billion for n = 45. It times out long before that. Add a cache or use the loop.

    Wrong
    print(ways(45))              # brute force: minutes, then a timeout
    Right
    from functools import cache@cachedef ways(n):    return 1 if n <= 1 else ways(n - 1) + ways(n - 2)print(ways(45))              # 1836311903, instantly
  • Writing dp[1] when n is 0

    minor

    dp = [0] * (n + 1) has a single cell when n = 0, so dp[1] = 1 raises IndexError. Return early for small n, or size the array as max(n + 1, 2).

    Wrong
    dp = [0] * (n + 1)dp[0] = 1dp[1] = 1                    # IndexError when n == 0
    Right
    if n <= 1:    return 1dp = [0] * (n + 1)dp[0] = dp[1] = 1
  • Taking max or min when counting

    major

    Counting ways adds the cases, because the groups never overlap. max and min belong to the optimisation cousins (house robber, min cost climbing). Mixing them up gives 1 for every n.

    Wrong
    dp[i] = max(dp[i - 1], dp[i - 2])   # counts nothing
    Right
    dp[i] = dp[i - 1] + dp[i - 2]        # count: add disjoint cases# cost version: cost[i] + min(best[i - 1], best[i - 2])

Interview tips

  • How to explain it

    • Look at the last move: a 1-step from n - 1 or a 2-step from n - 2, never both, so ways(n) = ways(n - 1) + ways(n - 2).
    • Base cases ways(0) = ways(1) = 1. The answer is F(n + 1).
    • Brute force is O(2ⁿ) because of overlapping subproblems; memo or table gives O(n); two variables give O(1) space.
  • Spot it in problems

    • "How many ways" to reach a target with a fixed set of move sizes.
    • The state is one number (the stair) and depends only on a few states just behind it.
    • Cousins: min cost climbing stairs, house robber, decode ways, domino tiling, Fibonacci number.
  • Memory tricks

    • FIB: From the previous two, Initialise the base cases, Build up to n.
    • 1, 1, 2, 3, 5, 8: ways to climb 0 to 5 stairs.
    • Like a ladder: each rung only depends on the rungs below it.
  • Watch out

    • ways(0) = 1, not 0.
    • Save the old value before overwriting in the two-variable loop.
    • Answers grow fast; variants often ask for the count modulo 10⁹ + 7.