Problem overview
The method climbStairs(n: number): number receives the number of steps in a staircase and returns how many distinct ways there are to reach the top. Each move climbs 1 or 2 steps, and the order of the moves matters: 1 then 2 and 2 then 1 are two different ways.
For n = 4 there are five ways: 1+1+1+1, 1+1+2, 1+2+1, 2+1+1 and 2+2. The method returns 5. The constraints say n is between 1 and 45 and that the answer always fits in a 32-bit integer.
Approach: build the counts from the bottom up
Listing every way works for 4 steps, but the number of ways grows quickly, so the code has to count without listing. The key observation is about the last move. To stand on step i, you arrived either from step i - 1 with a 1-step move or from step i - 2 with a 2-step move. Those two groups never overlap, because their last moves differ, and together they cover every way. So:
ways(i) = ways(i - 1) + ways(i - 2)
This is the Fibonacci recurrence. Writing it as a plain recursive function would recompute the same values over and over and take exponential time. Dynamic programming avoids that by solving the small cases first and reusing their answers. Here each answer depends only on the two before it, so there is no need for a whole table: two variables are enough.
The starting values are ways(0) = 1 and ways(1) = 1. Step 0 is the ground, and there is exactly one way to be on it: don't move. Counting it makes step 2 come out right, since 1 + 1 = 2 (either two 1-steps or one 2-step).
Step by step
- Create
prevwithlet, starting at 1. It holds the ways to reach the step two below the current one, starting with the ground. - Create
currthe same way, also 1. It holds the ways to reach step 1. Forn = 1the loop never runs, so this value is already the answer. - Loop with
ifrom 2 up to and includingn. Use<=: stepnis the top and needs its own count. At the start of each round,curris the count for stepi - 1andprevthe count for stepi - 2. - Store
prev + currin aconstnamedways. That is the count for stepi. - Slide the window up one step. Set
prev = currfirst, thencurr = ways. Doing it the other way around would overwrite the valueprevstill needs. - Return
curr. After the last round it holds the count for stepn.
Here is what the variables hold for n = 5:
start prev=1 curr=1
i=2 ways=2 prev=1 curr=2
i=3 ways=3 prev=2 curr=3
i=4 ways=5 prev=3 curr=5
i=5 ways=8 prev=5 curr=8
The function returns 8. The values 1, 2, 3, 5, 8 are the answers for 1 to 5 steps, so you can check them against the examples above.
The solution in TypeScript
class Solution {
climbStairs(n: number): number {
let prev = 1;
let curr = 1;
for (let i = 2; i <= n; i++) {
const ways = prev + curr;
prev = curr;
curr = ways;
}
return curr;
}
}
The TypeScript details worth knowing:
- Inferred types.
let prev = 1needs no annotation: TypeScript infersnumberfrom the initial value. The same goes forways, which isnumberbecause both operands are. letversusconst.prevandcurrchange in every round, so they needlet.waysis created fresh in each round and never reassigned, soconstfits, and its scope ends with the loop body.- No integer overflow, but limits.
numberis a double, so nothing wraps around. The result is still exact only up to2**53. The answers forn = 45andn = 46are1836311903and2971215073. The second no longer fits in a signed 32-bit integer, but in TypeScript it is still exact; the constraintn <= 45comes from languages with a 32-bitint. Far beyond that, precision goes:climbStairs(80)gives37889062373143900, which is not the true value. - The return annotation.
: numberafter the parameter list is erased when the code compiles to JavaScript. It documents the contract and lets the compiler check thereturn, but it does nothing at run time.
Complexity
Time: O(n). The loop runs n - 1 times and each round does a constant amount of work. The naive recursion without reuse takes exponential time, because it solves the same sub-staircases again and again.
Space: O(1). Only prev, curr, ways and i exist, no matter how large n is. A table of n + 1 counts would also work and would cost O(n) space.
Edge cases and common mistakes
n = 1. The loop condition2 <= 1is false from the start, so the function returns the initialcurr, which is 1.n = 2. One round runs:ways = 1 + 1 = 2. This is whyprevstarts at 1 and not 0.- Using
<in the loop. The function would stop one step short and return the count forn - 1. Forn = 3it would return 2 instead of 3. - Updating in the wrong order. Setting
curr = waysbeforeprev = currmakes both variables equal, and the counts stop growing correctly. - Counting combinations instead of sequences. The order of moves matters here, so
1+2and2+1both count. That is why the two groups of ways add instead of being merged. n = 0. It is outside the constraints. The function would return 1, matching the idea of one way to stay on the ground.
Testing
n = 1gives1.n = 2gives2.n = 3gives3.n = 4gives5.n = 10gives89.n = 45gives1836311903.
