Climbing Stairs
Count the ways to climb n stairs when each move is 1 or 2 steps, by building on smaller staircases.
The problem
You are at the bottom of a staircase with n steps. Each move takes you up either 1 step or 2 steps. Return the number of different move sequences that land you exactly on the top step.
Input n = 4
Output 5
The sequences are 1+1+1+1, 1+1+2, 1+2+1, 2+1+1 and 2+2.
Input n = 6
Output 13
ways(6) = ways(5) + ways(4) = 8 + 5.
Key constraint: n can be 45, and plain recursion would make billions of calls for that, so each smaller answer must be worked out once and reused.
How to spot the pattern
- You count the ways to reach a goal through small, repeated choices.
- The last move is 1 or 2 steps, so the answer for
nsplits into answers for smaller staircases. - Plain recursion would solve the same smaller staircases again and again.
The idea
State: ways(i) is the number of ways to reach step i. Your last move onto step i came from step i - 1 or from step i - 2, so the transition is ways(i) = ways(i - 1) + ways(i - 2), with ways(0) = ways(1) = 1. Each value needs only the two before it, so two variables are enough.
Brute force: Recurse on n - 1 and n - 2 without saving results, which takes O(2^n) time.
Step by step
- 1Start with
twoBack = ways(0) = 1andoneBack = ways(1) = 1. - 2For each step
ifrom 2 ton, computeways = oneBack + twoBack. - 3Shift the pair:
twoBacktakes the oldoneBack, andoneBacktakes the new value. - 4After the loop, return
oneBack, which now holdsways(n).
See the pattern move
The 1d dynamic programming pattern on a small example. Step through it, or press play.
Code
class Solution:
def climbStairs(self, n: int) -> int:
# ways(i) = ways(i - 1) + ways(i - 2), and only the last two values are needed
two_back, one_back = 1, 1 # ways(0) and ways(1)
for _ in range(2, n + 1):
two_back, one_back = one_back, one_back + two_back
return one_backComplexity
Time
O(n)
Space
O(1)
One pass from 2 to n that keeps only the last two values.
Watch out for
- Plain recursion without memoization: it recomputes the same steps and is far too slow for n = 45.
- Getting the base cases wrong:
ways(0) = 1(the empty climb) is what makesways(2)come out as 2.
Follow-up questions
What if you could also climb 3 steps at a time?
Add one more term, ways(i) = ways(i - 1) + ways(i - 2) + ways(i - 3), and keep three variables instead of two.
What if some steps are broken and can't be stepped on?
Set ways(i) = 0 for a broken step and use the same transition for every other step.
In Hinglish
Aakhri move ya toh 1 step tha ya 2 step, isliye `ways(n) = ways(n - 1) + ways(n - 2)`. Bas pichhle do numbers yaad rakho aur aage badho.