Climbing Stairs (LeetCode 70): Solution and Explanation

Easy
Math
Dynamic Programming
Memoization

You are climbing a staircase with n steps and can move up either one or two steps at a time. Count how many different sequences of moves take you exactly to the top.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A natural first attempt is to enumerate every sequence of 1s and 2s that adds up to n. Written as recursion, ways(n) tries a 1-step and a 2-step and adds the results. That is correct but exponential, because the same subproblems are solved over and over; ways(n - 2) is reached both directly and through ways(n - 1), and the duplication compounds at every level.

The useful observation is about the last move. Any way of reaching step i ends with either a single step from i - 1 or a double step from i - 2. Those two groups do not overlap and together cover every possibility, so ways(i) = ways(i - 1) + ways(i - 2). That is the Fibonacci recurrence, shifted by one: 1, 2, 3, 5, 8 and so on.

Once you have a recurrence where each value depends only on smaller values, you can fill a table from the bottom up. The reference solution handles the small cases directly (one step has 1 way, two steps have 2 ways), creates a dp array of size n + 1, seeds dp[1] and dp[2], and fills each later entry from the two before it. Every subproblem is computed exactly once, turning exponential time into linear time.

This problem is the standard first example of dynamic programming for a reason. The same three-part recipe (define what a subproblem means, find how it is built from smaller ones, then fill the answers in an order where the smaller ones are ready first) carries over directly to House Robber, Decode Ways, Min Cost Climbing Stairs and many grid path problems.

Approach: Bottom-up dynamic programming

  1. If n <= 2, return n, since there is 1 way to climb one step and 2 ways to climb two.
  2. Create dp = [0] * (n + 1) and set dp[1] = 1 and dp[2] = 2.
  3. Loop i from 3 to n inclusive.
  4. Set dp[i] = dp[i - 1] + dp[i - 2], combining paths whose last move is one step with paths whose last move is two steps.
  5. Return dp[n].

Step-by-step example

n = 5
  1. n is greater than 2, so build dp with dp[1] = 1 and dp[2] = 2.
  2. i = 3: dp[3] = dp[2] + dp[1] = 2 + 1 = 3.
  3. i = 4: dp[4] = dp[3] + dp[2] = 3 + 2 = 5.
  4. i = 5: dp[5] = dp[4] + dp[3] = 5 + 3 = 8.
  5. Return 8. For instance, the three ways to climb 3 steps are 1+1+1, 1+2 and 2+1.

Code: Python, Java, C++

1class Solution:
2    def climbStairs(self, n: int) -> int:
3        if n <= 2: return n
4        dp = [0] * (n + 1)
5        dp[1], dp[2] = 1, 2
6        
7        for i in range(3, n + 1):
8            dp[i] = dp[i - 1] + dp[i - 2]
9            
10        return dp[n]

Time and space complexity

Time

O(n)

The loop computes each of the n - 2 table entries once with a single addition.

Space

O(n)

The dp array stores n + 1 values. Since each entry only needs the previous two, this can be reduced to O(1) with two variables.

Other approaches

Two rolling variables (time O(n), space O(1))

Keep only the last two values and shift them forward each iteration. Identical logic and time, but constant memory, which is the usual follow-up.

Recursion with memoization (time O(n), space O(n))

Write the natural recursive definition and cache results in a dictionary. It is the top-down version of the same DP and is easy to derive, but it uses recursion depth proportional to n.

Common mistakes

  • Writing plain recursion without a cache. It recomputes the same values exponentially many times and times out around n = 40.
  • Indexing dp[2] when n is 1. The early return for n <= 2 prevents writing past the end of a two-element array.
  • Using range(3, n) instead of range(3, n + 1), which skips computing dp[n] and returns 0.
  • Treating the answer as fib(n) with the standard indexing where fib(1) = fib(2) = 1. The staircase count is shifted, so ways(n) = fib(n + 1).

Frequently asked questions

Why is Climbing Stairs a Fibonacci problem?

Every path to step i ends with a 1-step from i - 1 or a 2-step from i - 2, so the count is the sum of the counts for those two steps. That is the Fibonacci recurrence starting from 1 and 2.

Can Climbing Stairs be solved in O(1) space?

Yes. Since each value depends only on the previous two, keep two variables and update them in a loop instead of storing the whole table.

Is there a faster than O(n) solution?

Matrix exponentiation or Binet's closed-form formula can compute Fibonacci numbers in O(log n) arithmetic steps. For n up to 45 the linear loop is already instant.

What if you could take 1, 2 or 3 steps?

The recurrence becomes ways(i) = ways(i - 1) + ways(i - 2) + ways(i - 3). The same bottom-up table works with one more term.