DSADP1D

Climbing Stairs Visualizer

What is Climbing Stairs

To reach stair n you last stepped from n−1 or n−2. So the number of ways is Fibonacci: dp[n] = dp[n-1] + dp[n-2]. Memoizing (or filling bottom-up) turns an exponential tree into a linear scan.

  • Base: 1 way to stand on stair 1, 2 ways to reach stair 2 (1+1 or 2).
  • Overlap: ways(5) asks for ways(4) and ways(3); both need ways(3)/ways(2).
  • Rolling vars: only the last two answers are live, so space is O(1).

Brute force approach

Branch on the last step: f(n) = f(n-1) + f(n-2). The same f(k) is recomputed from many parents. Time O(2^n).

ways(n) asks for ways(n-1) and ways(n-2). The brute-force tree repeats those calls. Memoization stores each n the first time it is solved.

Try a small input

Keep n at 4 or below so the whole recursion tree fits in the canvas. ways(1) = 1 and ways(0) = 1, so ways(2) = 2.

Answer: 0 Brute calls: 0 Memo calls: 0 Calls saved: 0
Recursive brute force
def ways(n):
if n <= 1: return 1
return ways(n-1) + ways(n-2)
Step 0

Memoized approach

Each stair is solved once and reused. Fill dp[1..n] or keep two rolling numbers. Time O(n), space O(1).

Each state is solved once. A dashed node is a cache hit: the call returns immediately and that branch stops.

Memoized recursion
def ways(n, memo):
if n in memo: return memo[n]
if n <= 1: return 1
memo[n] = ways(n-1) + ways(n-2)
return memo[n]
Step 0

How this visualizer works

Default n = 5. Watch dp[1]..dp[5] fill: 1, 2, 3, 5, 8. Change n and replay. Step through the DP table. The live code on the right is the DP recurrence — brute force is shown in Implementations below so you can see why it TLE.

Interactive DP trace

dp_table.state

Input
DP table
Cell being filled
Source / window
Already computed

current_action

Load an input, then press Play or Step.

live_trace.py — DP fill

1def climb(n):
2if n <= 2: return n
3a, b = 1, 2
4for i in range(3, n+1):
5a, b = b, a+b
6return b

stdout — decision log

// each table write is recorded here
Speed Ready

Pseudocode & Complexity

dp_recurrence.txt

1def climb(n):
2if n <= 2: return n
3a, b = 1, 2
4for i in range(3, n+1):
5a, b = b, a+b
6return b

complexity.md

OperationTime
Each stairO(1)
All stairsO(n)
SpaceO(1)

Brute force explores the same subproblems many times and will TLE on the hidden tests. The DP codes below reuse each answer once.

Implementations

dp.py

1def climb_brute(n):
2if n <= 2:
3return n
4return climb_brute(n - 1) + climb_brute(n - 2)
1def climb_dp(n):
2if n <= 2:
3return n
4a = 1
5b = 2
6for i in range(3, n + 1):
7nxt = a + b
8a = b
9b = nxt
10return b
1int climb_brute(int n) {
2if (n <= 2) {
3return n;
4}
5return climb_brute(n - 1) + climb_brute(n - 2);
6}
1int climb_dp(int n) {
2int a;
3int b;
4int i;
5int nxt;
6if (n <= 2) {
7return n;
8}
9a = 1;
10b = 2;
11for (i = 3; i <= n; i++) {
12nxt = a + b;
13a = b;
14b = nxt;
15}
16return b;
17}