Typorithm · easy

Climbing Stairs

▷ Interactive algorithm labclimbing-stairs-dpdynamic-programmingsequencespace-optimized
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Climbing Stairs

0%

Dynamic Programming

Climbing Stairs is Fibonacci with a story: each step can be reached from one or two steps below.

The state is the number of ways to reach a stair.

The transition adds the previous two states.

Only two variables are needed because older states are never read again.

Preparing algorithm lab…
01

State: ways to reach step i.

02

Base: step 1 has 1 way, step 2 has 2 ways.

03

Transition: ways[i-1] + ways[i-2].

04

Space can be O(1).

function climbStairs(n) {
  if (n <= 2) return n;

  let oneStepBefore = 2;
  let twoStepsBefore = 1;

  for (let step = 3; step <= n; step++) {
    const current = oneStepBefore + twoStepsBefore;
    twoStepsBefore = oneStepBefore;
    oneStepBefore = current;
  }

  return oneStepBefore;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Small stairs

There are n ways for 1 or 2 stairs.

if (n <= 2) return n

2. Previous state

Ways to reach step 2.

let oneStepBefore = 2

3. Build upward

Compute each next stair count from earlier counts.

for (let step = 3; step <= n; step++)

4. Ways recurrence

Reach current from one step below or two steps below.

const current = oneStepBefore + twoStepsBefore

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Climbing Stairs: Visual Walkthrough & Practice · Typorithm | ApplyDjinn