Climbing Stairs
Master this topic with zero to advance depth.
Climbing Stairs
You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Visual Representation
n = 3
Ways:
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
Total: 3 ways
Recursion Tree:
(3)
/ \
(2) (1)
/ \ |
(1) (0) (0)Examples
- 1 step + 1 step
- 2 steps
- 1 + 1 + 1
- 1 + 2
- 2 + 1
Level I: Brute Force (Recursion)
Intuition
To reach step n, you could have come from either step n-1 (by taking 1 step) or step n-2 (by taking 2 steps). Thus, the total ways . This is exactly the Fibonacci sequence.
Thought Process
- Base cases: If or , there is only 1 way.
- Recursive step: Return .
Pattern Identification
This is Plain Recursion. The bottleneck is that it re-calculates the same steps many times, leading to an exponential time complexity.
Detailed Dry Run
| Call | n | Returns | Action |
|---|---|---|---|
| 1 | 3 | f(2) + f(1) | Recurse |
| 2 | 2 | f(1) + f(0) | Recurse |
| 3 | 1 | 1 | Base Case |
| 4 | 0 | 1 | Base Case |
Level II: Memoization (Top-Down)
Intuition
Cache the result of climb(n) using a memo table so each stair count is computed only once.
Visual
climb(5)
climb(4) --cached after first call!
climb(3) --cached after first call!
...
Only N unique calls made.Detailed Dry Run
climb(4) = climb(3) + climb(2). climb(3) = climb(2) + climb(1). Both branches cache climb(2)=2.
â ī¸ Common Pitfalls & Tips
Python's lru_cache handles the caching automatically. In other languages, a HashMap or array of size N+1 is needed.
Level III: Optimal (DP + Space Optimization)
Intuition
Thought Process
Since we only need the last two results ( and ) to calculate the current one, we can use two variables instead of a full DP array. This is the Iterative approach with O(1) Space.
Logic Steps
- Initialize
prev1 = 1(for step 1) andprev2 = 1(for step 0). - Loop from 2 to
n. - Calculate
current = prev1 + prev2. - Update
prev2 = prev1andprev1 = current.
Detailed Dry Run
n = 3
| i | current | prev1 | prev2 | Action |
|---|---|---|---|---|
| - | - | 1 | 1 | Init |
| 2 | 1+1=2 | 2 | 1 | Update variables |
| 3 | 2+1=3 | 3 | 2 | Update variables |
â ī¸ Common Pitfalls & Tips
Be careful with base cases. If is considered 1 way (doing nothing), the logic holds. For , it's also 1 way. The loop should start from 2.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.