Climbing Stairs

Easy

Topics
Dynamic ProgrammingMath

You are climbing a staircase with n steps. Each time you can climb 1 or 2 steps. In how many distinct ways can you reach the top?

Example 1

1+12
Each chip is one distinct way to climb 2 steps taking one or two at a time. Order counts as part of the identity, so 1+2 and 2+1 are two different climbs. The answer is how many there are, 2.
Each chip is one climb, written as its sequence of step sizes.
Input:  n = 2
Output: 2

Example 2

1+1+11+22+1
Input:  n = 3
Output: 3

Constraints

  • 1 <= n <= 45
Editorial — intuition, approach, complexity and pitfalls

Intuition

To land on step n your last move came from step n-1 (a single step) or step n-2 (a double step). So the number of ways to reach n is the sum of the ways to reach those two steps.

That is exactly the Fibonacci recurrence, computable in O(1) space.

Approach

  1. There is 1 way to be at the bottom and 1 way to reach step 1.
  2. Roll two counters forward: next = a + b.
  3. After n steps the counter holds ways(n).

Walkthrough

n = 4
steps: 1, 1, 2, 3, 5
ways(0)=1 ways(1)=1 ways(2)=2 ways(3)=3 ways(4)=5

Complexity

  • Time — O(n): a single loop to n.
  • Space — O(1): only the last two counts are kept.

Common Pitfalls

  • Keep the n <= 2 base case. The loop seeds prev, cur = 1, 2, which already assumes two steps exist, so without the guard n = 1 returns 2 instead of 1.
  • This is Fibonacci offset by one, not Fibonacci. Lining the indices up wrong is the usual source of an answer that is right for every input except the smallest.

Full Solution — all languages

class Solution:
    def climbStairs(self, n):
        if n <= 2:
            return n
        prev, cur = 1, 2
        for _ in range(3, n + 1):
            prev, cur = cur, prev + cur
        return cur
SensAI
Beta
Tap the mic to stop voice mode