Climbing Stairs
Count the distinct ways to reach the top of an n-step staircase when hopping 1 or 2 steps at a time. The premier gentle introduction to Dynamic Programming and state transition.
Problem Statement
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?
Examples & Constraints
- 1 <= n <= 45
Space-Optimized DP (Fibonacci State Transition)
Optimal ApproachRecognize that ways to reach step n is ways(n - 1) + ways(n - 2). Maintain only two previous states for O(1) space.
A single loop from step 3 up to N.
Only two variables (prev1, prev2) are maintained in memory.
Underlying algorithmic logic
The Core Mental Model: Look At Your Last Hop
Instead of thinking forward from the bottom of the stairs, stand at the top step (`n`) and look backwards:
Because you can only jump 1 step or 2 steps, your final hop onto step n could have ONLY originated from two places:
- You were on step `n - 1` and hopped 1 step.
- You were on step `n - 2` and hopped 2 steps.
There is no other physical way to land on step n.
Therefore, the total distinct ways to reach step n is simply the sum of ways to reach both preceding steps:ways(n) = ways(n - 1) + ways(n - 2)
Why This Is Fibonacci In Disguise
Base cases:
ways(1) = 1(just [1])ways(2) = 2([1+1], [2])ways(3) = 1 + 2 = 3ways(4) = 2 + 3 = 5
Avoiding The O(2ⁿ) Recursive Trap
If you code this as naive recursion return climb(n - 1) + climb(n - 2), the computer re-computes subproblems exponentially. At n = 45, that takes 2⁴⁵ ≈ 35 trillion calculations!
Step-by-Step Engineering Flow (Two Variables in O(1) Space)
- Handle Base Cases: If
n <= 2, returnnimmediately (n = 1has 1 way;n = 2has 2 ways). - Initialize Two Running States:
- Set
prev1 = 1(ways to reach step 1). - Set
prev2 = 2(ways to reach step 2).
- Iterative Window Slide: For each step
ifrom 3 up ton:
- Calculate current step ways:
curr = prev1 + prev2. - Shift the state window forward:
prev1 = prev2, thenprev2 = curr.
- Return Answer: When the loop finishes,
prev2holds the total distinct ways to reach stepn.
This yields an optimal `O(n)` time and `O(1)` memory solution.
Step-by-step execution walkthrough
For n = 1 -> 1 way. For n = 2 -> 2 ways.
curr = 1 + 2 = 3. Shift: prev1 = 2, prev2 = 3.
curr = 2 + 3 = 5. Shift: prev1 = 3, prev2 = 5.
- •Optimal O(n) runtime
- •Constant O(1) space
- •Introductory paradigm for dynamic programming state transitions
- •None for N <= 45
Code Implementations
Ready-to-useCopy & paste production-ready solutions for Space-Optimized DP (Fibonacci State Transition) in your language of choice
def climb_stairs(n: int) -> int:if n <= 2:return nprev1, prev2 = 1, 2for _ in range(3, n + 1):prev1, prev2 = prev2, prev1 + prev2return prev2if __name__ == "__main__":print(f"climb_stairs(2): {climb_stairs(2)}")print(f"climb_stairs(3): {climb_stairs(3)}")
Understand Recursion & Fibonacci Visually
Observe compiler stack frames tracking self-referencing operations and tree calculations. Test live edge cases and watch memory state transitions step-by-step.
Frequently Asked Questions
Related Logic & Algorithm Problems
Best Time to Buy and Sell Stock
Determine the maximum single-transaction profit from daily stock prices. A classic demonstration of how tracking a running minimum transforms an O(n²) pair search into an O(n) single pass.
Two Sum
Find the two numbers in an array that sum up to a target value. The quintessential problem for learning how to trade memory for speed using a Hash Map.
Maximum Subarray (Kadane's Algorithm)
Find the contiguous slice of an array that yields the largest sum. Kadane's algorithm demonstrates the art of shedding negative historical baggage in O(n) linear time.