Climbing stairs
easy 15 minClimbing stairs asks how many different sequences of 1-steps and 2-steps reach stair n.
See it run
Watch the brute-force tree redo the same stairs, then prune it with a memo, flatten it into a dp array and shrink it to two variables.
Operations
Brute recursion: ways(5)
Ask: how did the last move reach stair n? Either a 1-step from n - 1 or a 2-step from n - 2, so ways(n) = ways(n - 1) + ways(n - 2). Coded as plain recursion, each call makes two more and the same subtrees appear again and again.
Step 1 of 10
One question, split by the last move
ways(5) = ?
We want ways(5): the number of different sequences of 1-steps and 2-steps that land exactly on stair 5. Every such sequence ends with either a 1-step (from stair 4) or a 2-step (from stair 3), never both.
Step 1: One question, split by the last move
def ways(n): if n <= 1: # 0 steps left: 1 way (stand still); 1 step left: 1 way return 1 one = ways(n - 1) # last move was a 1-step, from stair n - 1 two = ways(n - 2) # last move was a 2-step, from stair n - 2 return one + two- Time
- O(2ⁿ), exactly Θ(φⁿ)
- Space
- O(n) call stack
- ways(5)
- 15 calls
- ways(20)
- 21,891 calls
- ways(45)
- 3.67 billion calls
Draw the tree for n = 5 once and circle the repeated labels. If the same call shows up twice, a cache will pay off.
In the real world
The same climbing stairs doing real jobs. Pick one and step through it.
The climber from the original visualizer tries every sequence of 1-steps and 2-steps up a 4-stair flight, one path at a time, so you can count the 5 ways by hand before trusting the formula.
Step 1 of 8
At the bottom of 4 stairs
- startyou
- 1
- 2
- 3
- top
Each move is a 1-step or a 2-step. We list the paths in a fixed order, trying a 1-step before a 2-step at every choice, so none is missed or repeated.
Step 1: At the bottom of 4 stairs
def all_paths(n, path=()): if n == 0: print("+".join(map(str, path))) return for step in (1, 2): if step <= n: all_paths(n - step, path + (step,))all_paths(4) # 1+1+1+1, 1+1+2, 1+2+1, 2+1+1, 2+2Common mistakes
The bugs interviewers watch for, with the fix beside each.
Setting dp[0] = 0
criticaldp[0] counts the empty path, which is one way to stand on stair 0. With dp[0] = 0, dp[2] = dp[1] + dp[0] = 1 instead of 2, and every later answer is wrong. If you prefer to avoid dp[0], start from dp[1] = 1 and dp[2] = 2 instead.
Wrongdp[0], dp[1] = 0, 1# dp[2] = 1, dp[3] = 2 ... off by one placeRightdp[0], dp[1] = 1, 1 # empty path counts as one way# dp[2] = 2, dp[3] = 3, dp[5] = 8Copying Fibonacci's base cases
majorFibonacci returns n for n <= 1, so fib(0) = 0. Climbing stairs needs ways(0) = 1. Pasting the Fibonacci code computes F(n) instead of F(n + 1): ways(5) comes out as 5, not 8.
Wrongdef ways(n): if n <= 1: return n # ways(0) = 0: wrong for stairs return ways(n - 1) + ways(n - 2)Rightdef ways(n): if n <= 1: return 1 # ways(0) = ways(1) = 1 return ways(n - 1) + ways(n - 2)Updating the two variables in the wrong order
criticalOverwriting prev1 before saving it into prev2 loses the old value, so the sum uses the new one twice and the numbers double instead of following Fibonacci.
Wrongcurr = prev1 + prev2prev1 = currprev2 = prev1 # this is now curr, not the old prev1Rightcurr = prev1 + prev2prev2 = prev1 # save the old value firstprev1 = curr# or in one line: prev2, prev1 = prev1, prev1 + prev2Plain recursion for real inputs
majorBrute force makes 2 · ways(n) - 1 calls: about 3.67 billion for n = 45. It times out long before that. Add a cache or use the loop.
Wrongprint(ways(45)) # brute force: minutes, then a timeoutRightfrom functools import cache@cachedef ways(n): return 1 if n <= 1 else ways(n - 1) + ways(n - 2)print(ways(45)) # 1836311903, instantlyWriting dp[1] when n is 0
minordp = [0] * (n + 1) has a single cell when n = 0, so dp[1] = 1 raises IndexError. Return early for small n, or size the array as max(n + 1, 2).
Wrongdp = [0] * (n + 1)dp[0] = 1dp[1] = 1 # IndexError when n == 0Rightif n <= 1: return 1dp = [0] * (n + 1)dp[0] = dp[1] = 1Taking max or min when counting
majorCounting ways adds the cases, because the groups never overlap. max and min belong to the optimisation cousins (house robber, min cost climbing). Mixing them up gives 1 for every n.
Wrongdp[i] = max(dp[i - 1], dp[i - 2]) # counts nothingRightdp[i] = dp[i - 1] + dp[i - 2] # count: add disjoint cases# cost version: cost[i] + min(best[i - 1], best[i - 2])
Interview tips
How to explain it
- Look at the last move: a 1-step from n - 1 or a 2-step from n - 2, never both, so ways(n) = ways(n - 1) + ways(n - 2).
- Base cases ways(0) = ways(1) = 1. The answer is F(n + 1).
- Brute force is O(2ⁿ) because of overlapping subproblems; memo or table gives O(n); two variables give O(1) space.
Spot it in problems
- "How many ways" to reach a target with a fixed set of move sizes.
- The state is one number (the stair) and depends only on a few states just behind it.
- Cousins: min cost climbing stairs, house robber, decode ways, domino tiling, Fibonacci number.
Memory tricks
- FIB: From the previous two, Initialise the base cases, Build up to n.
- 1, 1, 2, 3, 5, 8: ways to climb 0 to 5 stairs.
- Like a ladder: each rung only depends on the rungs below it.
Watch out
- ways(0) = 1, not 0.
- Save the old value before overwriting in the two-variable loop.
- Answers grow fast; variants often ask for the count modulo 10⁹ + 7.