Climbing Stairs
Count the ways to climb n stairs, 1 or 2 steps at a time
DSA, Easy, 1-D DP
Which structure or algorithm, and what does it cost.
A staircase has n steps, and you start on the ground, which counts as step 0. Each stride lifts you one step or two steps. Count the different stride sequences that end exactly on step n. Two sequences differ if any stride differs. For n = 0 the answer is 1, the empty sequence.
Examples
Constraints
- 0 <=
n<= 70. - The answer fits in a 64-bit signed integer.
Your answer must contain
- The simple method and why it is too slow
- The better method
- The best method and why it is correct
- Code
- Time and memory cost
- A hand trace of example 1
Target Aim for O(n) time and O(1) memory.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Think about the last stride. Which steps could you have stood on just before you landed on step n?
Hint 2 the approach
Write the counts for the first few steps by hand. Look for how each count relates to the counts before it.
Hint 3 the key step
The count for a step is the count one step back plus the count two steps back. Keep only those two numbers and slide them forward.
Walkthrough
Full walkthrough brute force to best
Brute force
Count every sequence by recursion: ways(n) = ways(n - 1) + ways(n - 2), with no memory of earlier answers. The same small cases are solved again and again. The number of calls is 2 x F(n + 1) - 1, where F is the Fibonacci sequence. That is about 6 x 10^14 calls for n = 70.
Better method
Memoised recursion. Save each answer the first time it is computed, so every step is solved once. That is O(n) time and O(n) memory for the saved answers and the recursion.
Best method
Each count needs only the two before it. The count for step 0 is 1 (no stride) and so is the count for step 1. For every next step, add the previous two counts. Keep just those two numbers and slide them forward. The answer is the count for step n. It is correct because every sequence ends with a one-step stride from step n - 1 or a two-step stride from step n - 2, and these two groups never overlap.
Hand trace
Run on n = 6. The counts for step 0 and step 1 are 1 and 1. Step 2: 1 + 1 = 2. Step 3: 1 + 2 = 3. Step 4: 2 + 3 = 5. Step 5: 3 + 5 = 8. Step 6: 5 + 8 = 13. The answer is 13.
Code
def count_ways(n):
prev, cur = 1, 1 # ways to land on step 0 and on step 1
for _ in range(n - 1):
prev, cur = cur, prev + cur
return curTime and memory
O(n) time, because the loop runs n - 1 times. O(1) memory, because only two numbers are kept.
Common mistakes
- Giving step 0 the count 0. A sequence with no strides counts as one way, so the first two counts are both 1.
- Adding the counts of the wrong steps, such as n - 1 and n - 3. Strides are one or two steps, so only the steps one and two back matter.
- Using plain recursion with no saved answers. It repeats the same work and is far too slow for n = 70.