Climbing Stairs
Understand the problem
You're climbing a staircase with n steps. Each time you can climb 1 or 2 steps. In how many distinct ways can you reach step n?
Example:
n = 2
output = 2 // [1+1] or [2]
n = 3
output = 3 // [1+1+1], [1+2], [2+1]Observation: the number of ways to reach step n = the number of ways to reach step n-1 (then take 1 step) + the number of ways to reach step n-2 (then take 2 steps).
That's exactly the Fibonacci recurrence — the intro problem of 1D dynamic programming (DP-1D).
Show the basic approach (slower)
O(2ⁿ) time, O(n) space (call stack)function climbStairs(n: number): number {
// Plain recursion — each call branches into 2 subcalls
if (n <= 1) return 1
return climbStairs(n - 1) + climbStairs(n - 2)
}The recursion tree branches twice at every node and is n levels deep → O(2ⁿ) calls.
Many subproblems are recomputed again and again — that's why you need dynamic programming.
Optimal solution
O(n) time, O(n) spacefunction climbStairs(n: number): number {
if (n <= 1) return 1
const dp = new Array<number>(n + 1)
dp[0] = 1 // 1 way to stand on step 0 (no climbing)
dp[1] = 1 // 1 way to reach step 1
for (let i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2] // recurrence relation
}
return dp[n]
}Store each step's result in a dp array so nothing is recomputed.
Each dp[i] only needs the previous 2 values — you can optimize further to O(1) space with 2 variables instead of a whole array.
Step-by-step trace
1function climbStairs(n: number): number {2 if (n <= 1) return 13 const dp = new Array<number>(n + 1)4 dp[0] = 1 // 1 way to stand on step 0 (no climbing)5 dp[1] = 1 // 1 way to reach step 16 for (let i = 2; i <= n; i++) {7 dp[i] = dp[i - 1] + dp[i - 2] // recurrence relation8 }9 return dp[n]10}Edge cases to remember
n=0 — already at the destination, 1 way (don't climb).
n=1 — exactly 1 way: take 1 step.
Large n (e.g. n=45) — the result is the 46th Fibonacci number (1,836,311,903), still within JavaScript's safe integer range (~2⁵³).
Space optimization: replace dp[] with 2 variables
prevandcurr, cutting O(n) space down to O(1).