Skip to content
DSA Patterns
Menu
Language
One-Dimensional DPLC #701 of 6Next →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Climbing Stairs

Problem (restated)

You can climb 1 or 2 steps. How many distinct ways to reach the top of n steps?

Intuition

ways(n) = ways(n-1) + ways(n-2). Fibonacci with rolling variables.

Approaches

1D DP

Unverified
Time O(n)Space O(1)

Idea. dp[i] = dp[i-1] + dp[i-2]; keep only two previous values.

Walkthrough. n=3 → 3 ways: 1+1+1, 1+2, 2+1.

Trade-offs. Closed form possible but DP is interview-clear.

Solution
export function climbStairs(n: number): number {
  if (n <= 2) return n;
  let a = 1, b = 2;
  for (let i = 3; i <= n; i++) {
    const c = a + b;
    a = b;
    b = c;
  }
  return b;
}
export function climbStairs(n: number): number {
  if (n <= 2) return n;
  let a = 1, b = 2;
  for (let i = 3; i <= n; i++) {
    const c = a + b;
    a = b;
    b = c;
  }
  return b;
}

Template connection

ways(i) = ways(i - 1) + ways(i - 2). Two rolling values store the previous step and the step before it.

Reflection

  • dp[i] = dp[i - 1] + dp[i - 2]. Each step is 1 or 2. n = 1 answers 1 and n = 2 answers 2.
  • Two rolling variables replace the array. The sequence is Fibonacci.
  • n = 3 answers 3. A larger n still needs only the two previous values.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Climb n=3 stairs, 1 or 2 at a time. dp[i] = ways to reach step i.

0
0
1
1
2
2
3
3

dp[0]=1 · dp[1]=1

Key:Active rangeMatchSettled