Problem overview
The method climbStairs receives n, the number of steps in a staircase, and returns in how many distinct ways you can climb to the top when each move is either 1 or 2 steps. Order matters: 1 step then 2 is a different way from 2 then 1.
For n = 4 there are five ways: 1+1+1+1, 1+1+2, 1+2+1, 2+1+1 and 2+2. For n = 3 there are three, and for n = 2 there are two. The constraints say 1 <= n <= 45 and that the answer fits in a 32-bit integer.
Approach: build up from the ground
Listing every sequence of moves would work for small n, but the number of sequences grows quickly. A better question is: how many ways are there to stand on step i? The last move onto step i was either a 1-step move from step i - 1 or a 2-step move from step i - 2. Those two groups of ways are different, and together they cover everything, so
ways(i) = ways(i - 1) + ways(i - 2)
This is dynamic programming: each answer reuses two smaller answers. It also means we never need the whole table. To compute step i we only look at the two steps below it, so two variables are enough and the extra space is O(1).
The starting values are ways(0) = 1 and ways(1) = 1. Step 0 is the ground, and there is exactly one way to be there: don't move. Counting it is what makes step 2 come out as 1 + 1 = 2.
Step by step
- Create
prevwithvar, starting at 1. It holds the ways to reach the step two below the current one, at first the ground. - Create
currthe same way, starting at 1. It holds the ways to reach step 1, which is one 1-step move. Forn = 1the loop never runs and this is already the answer. - Loop
iover2 to n. At the start of each round,curris the count for stepi - 1andprevthe count for stepi - 2. - Store
prev + currin avalnamedways. That is the count for stepi. - Shift the window. Set
prevtocurr, thencurrtoways. The order matters: assigningcurrfirst would destroy the valueprevneeds. - End with
curr. After the last round it holds the count for stepn.
The solution in Scala
class Solution {
def climbStairs(n: Int): Int = {
var prev = 1
var curr = 1
for (i <- 2 to n) {
val ways = prev + curr
prev = curr
curr = ways
}
curr
}
}
The Scala details worth a closer look:
varandval.prevandcurrchange every round, so they arevar.waysis created fresh in each round of the loop and never reassigned, so it is aval.2 to nincludesn. The range2 until nwould stop one step early. Whennis 1,2 to 1is empty and the loop is skipped.- The last expression is the result. The method's final line,
curr, is its value, so noreturnis needed. Intoverflow is silent. AnInthas 32 bits and wraps around without an error. The constraintn <= 45keeps the answer in range:climbStairs(45)gives 1836311903. Beyond that range the same code gives wrong numbers, for exampleclimbStairs(46)returns -1323752223 andclimbStairs(47)returns 512559680. Switching the variables toLongwould extend the range.
Complexity
Time: O(n). The loop runs n - 1 times and each round does a fixed amount of work.
Space: O(1). Only prev, curr, ways and the loop index are stored, however large n is. Keeping a full array of counts would be O(n).
Edge cases and common mistakes
n = 1. The loop is skipped and the method returnscurr, which is 1.- Starting
prevat 0. The ground has one way to be on it. With 0, step 2 would come out as 1 instead of 2. - Updating in the wrong order. If the loop writes
curr = waysand thenprev = curr, both variables end up equal toways. Forn = 5that version returns 16 instead of 8. - Using
untilinstead ofto. The loop then counts only up to stepn - 1and returns a number that is too small. - Overflow beyond the constraint. For
nabove 45 the result no longer fits in anInt, as shown above.
Testing
n = 1gives 1.n = 2gives 2.n = 3gives 3.n = 4gives 5.n = 5gives 8.n = 10gives 89.n = 45gives 1836311903.
The counts 1, 2, 3, 5, 8, 13 are the Fibonacci numbers: each is the sum of the two before it, which is the same rule the loop applies.
