Climbing Stairs – Solution & Complexity

1. Understand the Choices

  • At each move, you can climb either 1 step or 2 steps.
  • To reach step n, the last move must come from step n - 1 or step n - 2.
  • Therefore, ways to reach n equals ways to reach n - 1 plus ways to reach n - 2.

2. Recognize the Fibonacci Pattern

  • For n = 1, there is 1 way: 1.
  • For n = 2, there are 2 ways: 1+1 and 2.
  • Every later answer is the sum of the previous two answers.

3. Avoid Recomputing Subproblems

  • A naive recursive solution branches into n - 1 and n - 2 repeatedly.
  • That repeats the same calculations many times.
  • Dynamic programming stores or carries forward the previous answers instead.
def climb_stairs(n: int) -> int:
    if n <= 2:
        return n
    return climb_stairs(n - 1) + climb_stairs(n - 2)

4. Keep Only the Last Two Values

  • You do not need a full array because each state depends only on the previous two states.
  • Let one_back represent ways to reach the previous step.
  • Let two_back represent ways to reach the step before that.
def climb_stairs(n: int) -> int:
    if n <= 2:
        return n
    two_back = 1
    one_back = 2
    return one_back

5. Final Solution and Complexity

  • Iterate from step 3 through step n, adding the last two counts each time.
  • Time complexity is O(n).
  • Space complexity is O(1) because only two counts are stored.
def climb_stairs(n: int) -> int:
    if n <= 2:
        return n

    two_back = 1
    one_back = 2
    for _ in range(3, n + 1):
        current = one_back + two_back
        two_back = one_back
        one_back = current

    return one_back

FAQ

See also: