Climbing Stairs
You are climbing a staircase. It takes n steps to reach the top. Each time you can climb either 1 or 2 steps. Return the number of distinct ways you can climb to the top. The number of ways to reach step i has optimal substructure : it is exactly the ways to reach step i-1 plus the ways to reach step i-2, two smaller subproblems that keep getting asked for again. Cache each step as you compute it and build the table bottom-up from step 1 to step n.
Constraints
- 1 ≤ n ≤ 45
Example
n = 58Explanation ways(5) = ways(4) + ways(3) = 5 + 3 = 8, reusing the two answers computed right before it.
In plain terms
- Subproblem
- A smaller version of the same question — here, "how many ways to reach an earlier step?"
Build the ways table from step 1 up to step n
The whole table for n = 5 is laid out. dp[1] = 1 and dp[2] = 2 are the base cases; the rest are still empty.
What happens in this step
dp[1] = 1 (the only way: one single step) dp[2] = 2 (two single steps, or one double step) Every cell from dp[3] to dp[5] is still blank because it has not been worked out yet. These two base cases seed all of them.
Steps to visualize
- Set the base cases: ways(1) = 1 and ways(2) = 2.
- For every step i from 3 to n, set ways(i) = ways(i-1) + ways(i-2).
- Each new step reuses the two cells directly before it instead of recomputing them.
- The value at step n is the answer.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
The whole table for n = 5 is laid out. dp[1] = 1 and dp[2] = 2 are the base cases; the rest are still empty.
What happens in this step
dp[1] = 1 (the only way: one single step) dp[2] = 2 (two single steps, or one double step) Every cell from dp[3] to dp[5] is still blank because it has not been worked out yet. These two base cases seed all of them.
Solution
function climbStairs(n) {
if (n <= 2) return n;
let prev2 = 1;
let prev1 = 2;
for (let i = 3; i <= n; i++) {
const curr = prev1 + prev2;
prev2 = prev1;
prev1 = curr;
}
return prev1;
}- Time
- O(n)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
n = 5 | 8 | example from the docstring |
n = 2 | 2 | boundary base case, two steps |
n = 1 | 1 | smallest valid input, a single step |
n = 3 | 3 | first step that combines both base cases |
n = 10 | 89 | several steps of accumulation |
n = 45 | 1836311903 | upper bound of the constraint range |