Climbing Stairs
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Dynamic Programming.
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
Input: n = 2
Output: 2
- 1 step + 1 step
- 2 steps
Input: n = 3
Output: 3
- 1 + 1 + 1
- 1 + 2
- 2 + 1
Approach 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.
⏱ O(2^n)💾 O(n) due to recursion stack
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 |
Approach 2
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.⏱ O(N)💾 O(N)
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.Approach 3
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.
⏱ O(n)💾 O(1)
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.
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.