Skip to main content
49

Climbing Stairs

Easydynamic programming

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:1-D Dynamic ProgrammingRead the beginner guide

A staircase has n steps. Each move, you climb either 1 or 2 steps. In how many distinct ways can you reach the top?

Understand the problem

  • You start at the bottom (step 0) and want to land exactly on step n.
  • A "way" is a sequence of moves, so order matters: 1 + 2 and 2 + 1 are two different ways.
  • You only need how many ways there are, not the ways themselves.

Example 1

text
Input:  n = 2
Output: 2

1 + 1, or 2.

Example 2

text
Input:  n = 3
Output: 3

1 + 1 + 1, 1 + 2, 2 + 1.

Example 3

text
Input:  n = 4
Output: 5

1+1+1+1, 1+1+2, 1+2+1, 2+1+1, 2+2.

Constraints

  • 1 <= n <= 45

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    The ways to reach step n are the ways to reach step n - 1 (then take 1 step) plus the ways to reach step n - 2 (then take 2 steps), so compute this from the bottom up, keeping only the last two values.

    This is your first dynamic programming problem

    Dynamic programming (DP) solves a problem by:

    1. expressing the answer in terms of answers to smaller versions of the same problem, and
    2. computing each smaller answer only once, usually from the smallest up.

    The beginner guide explains DP in more detail. This problem is the classic first example.

    The key insight: look at the last move

    To stand on step n, your last move was either:

    • a 1-step from step n - 1, or
    • a 2-step from step n - 2.

    Every way to reach the top ends in exactly one of those, so:

    text
    ways(n) = ways(n - 1) + ways(n - 2)
    ways(1) = 1        (just "1")
    ways(2) = 2        ("1 + 1" or "2")

    (If this looks familiar, it's the Fibonacci sequence: each number is the sum of the two before it.)

    The naive approach (and why it's slow)

    Writing that formula directly as a recursion works, but it's very slow:

    text
    ways(5) calls ways(4) and ways(3)
    ways(4) calls ways(3) and ways(2)   ← ways(3) is computed AGAIN
    ...

    The same values are recomputed again and again, and the number of calls roughly doubles with each step: O(2^n). For n = 45, that's trillions of calls.

    Computing each value once

    Two standard fixes:

    • Memoization (top-down): keep the recursion, but save each ways(i) the first time you compute it, and reuse it after that.
    • Tabulation (bottom-up): start from ways(1) and ways(2) and compute ways(3), ways(4), ... up to n in a loop.

    Bottom-up has one more bonus: each value only needs the previous two, so you don't even need an array. Two variables are enough.

    Step by step

    n = 5. We track oneBack (ways to reach the previous step) and twoBack (the step before that). Step 0 counts as 1 way (stand still), and step 1 is 1 way:

    Step itwoBackoneBackways(i) = oneBack + twoBack
    2112
    3123
    4235
    5358

    There are 8 ways to climb 5 steps.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(n). One loop iteration per step.
    • Memory: O(1). Two variables.

    Common mistakes

    • Plain recursion without saving results. Correct, but times out.
    • Off-by-one base cases. Check small inputs by hand: n = 1 → 1, n = 2 → 2, n = 3 → 3.
    • Updating the two variables in the wrong order. Compute the new value before overwriting the old ones (or update both at once, as the solution does).

    Going deeper

    These two steps, (1) find the formula from smaller answers, (2) compute it bottom-up in the right order, are the template for every problem in this section. House Robber is the next step: the same shape, but with a choice ("take it or skip it") at each position.

    Reference solution

    js
    /**
     * @param {number} n
     * @return {number}
     */
    export default function climbStairs(n) {
      // ways(i) = ways(i - 1) + ways(i - 2): the last move was a 1-step or a 2-step.
      // Each value only needs the previous two, so two variables replace a whole array.
      let oneBack = 1 // ways to reach step i - 1
      let twoBack = 1 // ways to reach step i - 2 (step 0: standing at the bottom)
      for (let i = 2; i <= n; i++) {
        // Compute ways(i), then slide the window forward by one step (both at once).
        ;[twoBack, oneBack] = [oneBack, oneBack + twoBack]
      }
      return oneBack
    }
    ts
    export default function climbStairs(n: number): number {
      // ways(i) = ways(i - 1) + ways(i - 2): the last move was a 1-step or a 2-step.
      // Each value only needs the previous two, so two variables replace a whole array.
      let oneBack = 1 // ways to reach step i - 1
      let twoBack = 1 // ways to reach step i - 2 (step 0: standing at the bottom)
      for (let i = 2; i <= n; i++) {
        // Compute ways(i), then slide the window forward by one step (both at once).
        ;[twoBack, oneBack] = [oneBack, oneBack + twoBack]
      }
      return oneBack
    }
    python
    def climb_stairs(n: int) -> int:
        # ways(i) = ways(i - 1) + ways(i - 2): the last move was a 1-step or a 2-step.
        # Each value only needs the previous two, so two variables replace a whole list.
        one_back, two_back = 1, 1  # ways to reach steps i - 1 and i - 2 (step 0: the bottom)
        for _ in range(2, n + 1):
            # Compute ways(i), then slide the window forward by one step (both at once).
            one_back, two_back = one_back + two_back, one_back
        return one_back