Climbing Stairs - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

Problem

Count the number of distinct ways to reach step n when each move can be either 1 step or 2 steps.

Base Cases

  • n = 1 → exactly 1 way: take a single 1-step.
  • n = 2 → exactly 2 ways: 1 + 1 (two 1-steps) or 2 (one 2-step).

Key Insight (Recurrence)

Let Ways(i) denote the number of ways to reach step i. To reach step i, you must come either from step i − 1 (taking 1 step) or from step i − 2 (taking 2 steps):
Ways(i) = Ways(i − 1) + Ways(i − 2)  (Fibonacci pattern).

Iterative DP with Rolling State

We avoid building an entire DP array because only the two most recent values are required. We initialize with the base cases:

  • prevWays = 1 → represents Ways(1).
  • currentWays = 2 → represents Ways(2).

For each step i from 3 to n:

  • At the start of iteration i:
    • currentWays holds Ways(i − 1) (the number of ways to reach step i − 1).
    • prevWays holds Ways(i − 2) (the number of ways to reach step i − 2).
  • We then compute nextWays = currentWays + prevWays, which represents the number of ways to reach step i (Ways(i)).
  • After this calculation, we roll the state forward:
    • currentWaysWays(i) (just computed as nextWays).
    • prevWaysWays(i − 1) (the old currentWays).

👉 This reassignment ensures that at the end of each iteration, the variables still correctly represent Ways(i − 1) and Ways(i), where i is the latest step index processed.

Termination & Output

The loop runs for i = 3 … n. When it finishes, the most recent step is n, so currentWays = Ways(n). 📌 The final answer is in currentWays because, by construction, it always tracks the number of ways to reach the latest step.

Time Complexity

The algorithm iterates once through the steps from 3 to n, performing only constant-time operations (addition and variable reassignment) at each iteration. Therefore, the time complexity is:

O(n) — linear in the input size n.

Space Complexity

The algorithm only maintains two variables — prevWays and currentWays — instead of storing all values in a DP array. Therefore, the space complexity is:

O(1) — constant extra space, independent of the input size n.

Visucodize editorial solution titled JS Solution for LeetCode's Climbing Stairs coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/climbing-stairs.