Climbing Stairs

Pattern: 1D DP

easy

To reach step n, the last move was 1 step (from n - 1) or 2 steps (from n - 2), so ways(n) = ways(n - 1) + ways(n - 2). Two variables are enough.

The problem

You climb n steps, 1 or 2 at a time. Return how many different ways there are. n = 2 gives 2; n = 3 gives 3.

Think first

  • What was the last move?
  • How many ways reach the step before it?
  • What are the smallest cases?

Hints

    Brute force, and why it fails

    Recursion trying both moves: O(2ⁿ).

    The key insight

    Every way to step n ends in exactly one of two last moves, so the counts add, and each count is needed only once.

    Dry run

    ways1 1

    ways(0) = 1, ways(1) = 1.

    Step 1 of 3

    The plan

    a = b = 1
    repeat n - 1 times: a, b = b, a + b
    return b
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    Two numbers updated n times.

    Edge cases

    • n = 1: 1.
    • n = 2: 2.
    • n = 45 still fits in 32 bits.
    I've built my logic, show the code

    Java

    class Solution {
        public int climbStairs(int n) {
            int prev = 1, cur = 1;                  // ways to reach step i - 1 and step i
            for (int i = 2; i <= n; i++) {
                int next = prev + cur;              // the last move was a 1-step or a 2-step
                prev = cur;
                cur = next;
            }
            return cur;
        }
    }

    C++

    class Solution {
    public:
        int climbStairs(int n) {
            int prev = 1, cur = 1;                  // ways to reach step i - 1 and step i
            for (int i = 2; i <= n; i++) {
                int next = prev + cur;              // the last move was a 1-step or a 2-step
                prev = cur;
                cur = next;
            }
            return cur;
        }
    };

    Python

    class Solution:
        def climbStairs(self, n: int) -> int:
            prev = cur = 1                          # ways to reach step i - 1 and step i
            for _ in range(2, n + 1):
                prev, cur = cur, prev + cur         # the last move was a 1-step or a 2-step
            return cur

    Common mistakes

    • Starting with ways(1) = 2.
    • Recursion without memoisation.

    Similar problems