Browse curriculum

Climbing Stairs Visualization

The Climbing Stairs problem asks for the number of distinct ways to reach the top of a staircase when you can take 1 or 2 steps at a time. Step through it in the interactive Climbing Stairs visualization below.

READY

0

1

2

3

4

5

 

Initialize DP array of size 6

Next

Base Cases: dp[0]=1 (Ground), dp[1]=1 (1 Step)

Stairs

5

Intuition

If you are at step n, you must have come from either step n-1 (taking 1 step) or step n-2 (taking 2 steps). Thus, the number of ways to reach step n is simply the sum of ways to reach the two previous steps. This structure is identical to the Fibonacci sequence.

Concept

Recurrence Relation:

Ways(n) = Ways(n-1) + Ways(n-2)

Base Cases:

  • Ways(0) = 1 (Standing on the ground is 1 way)
  • Ways(1) = 1 (One step to reach step 1)
  • Ways(2) = 2 (1+1 or 2)

This is a classic 1D Dynamic Programming problem where the state depends only on the previous two states.

How Climbing Stairs Works

Tabulation Algorithm:

  1. Initialize an array dp of size n+1.
  2. Set dp[0] = 1, dp[1] = 1.
  3. Iterate from i = 2 to n.
  4. For each step, set dp[i] = dp[i-1] + dp[i-2].
  5. The answer is dp[n].

Climbing Stairs Visualization, Step by Step

Visualizing the path:

  • Step 0 & 1: Fixed starting points.
  • Step 2: Sum of Step 1 and Step 0.
  • Step 3+: Rolling sum of the previous two values.

When to Use

Applications:

  • Counting permutations with restricted step sizes.
  • Foundation for more complex "path counting" problems (e.g., Min Cost Climbing Stairs).

When NOT to Use

  • Variable Steps: If step sizes change dynamically, the simple 2-state relation breaks (though DP still applies with modification).

How to Identify

"Count distinct ways", "Review previous choices".

Practice it on interview problems

LeetCode problems solved with the Dynamic Programming pattern, each with a step-by-step visualizer:

All Dynamic Programming problems

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description

Compare its cost with every other algorithm in the Big O cheat sheet.

Frequently Asked Questions

How is it related to Fibonacci?

To reach the Nth stair, you can either come from (N-1) by taking 1 step OR from (N-2) by taking 2 steps. Thus, Ways(N) = Ways(N-1) + Ways(N-2).


Adding more step options?

If you can take 1, 2, or 3 steps, the relation becomes Ways(N) = Ways(N-1) + Ways(N-2) + Ways(N-3).


Is it Top-Down or Bottom-Up?

Both work! Top-down says "I can come from below." Bottom-up says "From here, I can go higher."