Climbing Stairs – Solution & Complexity
Quick practice for Climbing Stairs: 3 reasoning beats, no typing
Watch: Climbing Stairs with dynamic programming
To reach step n, your last move was from step n−1 or n−2, so ways(n) = ways(n−1) + ways(n−2): Fibonacci. Plain recursion repeats work exponentially; building up from the bottom with two variables is O(n) time and O(1) space.
Solution Walkthrough
Step 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 stepn - 1or stepn - 2. - Therefore, ways to reach
nequals ways to reachn - 1plus ways to reachn - 2.
Step 2: Recognize the Fibonacci Pattern
- For
n = 1, there is 1 way:1. - For
n = 2, there are 2 ways:1+1and2. - Every later answer is the sum of the previous two answers.
- For
Step 3: Avoid Recomputing Subproblems
- A naive recursive solution branches into
n - 1andn - 2repeatedly. - That repeats the same calculations many times.
- Dynamic programming stores or carries forward the previous answers instead.
- A naive recursive solution branches into
Step 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_backrepresent ways to reach the previous step. - Let
two_backrepresent ways to reach the step before that.
Step 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.
- Iterate from step 3 through step