Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find how many ways we can climb stairs in Python
Suppose we have a staircase with n steps, and we can climb up either 1 or 2 steps at a time. We need to find the number of unique ways we can climb the staircase.
The order of the steps matters, so each different sequence counts as a unique way. If the answer is very large, we return the result modulo 10^9 + 7.
For example, if n = 5, there are 8 unique ways ?
- 1, 1, 1, 1, 1
- 2, 1, 1, 1
- 1, 2, 1, 1
- 1, 1, 2, 1
- 1, 1, 1, 2
- 1, 2, 2
- 2, 1, 2
- 2, 2, 1
How It Works
This is a classic dynamic programming problem that follows the Fibonacci sequence. To reach step n, we can either come from step n-1 (taking 1 step) or from step n-2 (taking 2 steps).
The recurrence relation is: ways(n) = ways(n-1) + ways(n-2)
Algorithm Steps
- Create a
dparray of sizen+1and initialize with 0 - Set
dp[0] = 1(one way to stay at ground) anddp[1] = 1(one way to reach step 1) - For each step
ifrom 2 ton, calculatedp[i] = dp[i-1] + dp[i-2] - Return
dp[n] mod (10^9 + 7)
Example
def climb_stairs(n):
MOD = (10**9) + 7
# Base cases
if n == 0:
return 1
if n == 1:
return 1
# DP array to store number of ways
dp = [0] * (n + 1)
dp[0] = 1 # One way to stay at ground
dp[1] = 1 # One way to reach step 1
# Fill the dp array
for i in range(2, n + 1):
dp[i] = (dp[i-1] + dp[i-2]) % MOD
return dp[n]
# Test with n = 5
result = climb_stairs(5)
print(f"Number of ways to climb {5} steps: {result}")
# Test with smaller values
for n in range(1, 6):
print(f"n = {n}: {climb_stairs(n)} ways")
Number of ways to climb 5 steps: 8 n = 1: 1 ways n = 2: 2 ways n = 3: 3 ways n = 4: 5 ways n = 5: 8 ways
Space-Optimized Solution
Since we only need the previous two values, we can optimize space complexity to O(1) ?
def climb_stairs_optimized(n):
MOD = (10**9) + 7
if n <= 1:
return 1
prev2 = 1 # ways to reach step (i-2)
prev1 = 1 # ways to reach step (i-1)
for i in range(2, n + 1):
current = (prev1 + prev2) % MOD
prev2 = prev1
prev1 = current
return prev1
# Test the optimized version
print(f"Optimized solution for n=10: {climb_stairs_optimized(10)}")
Optimized solution for n=10: 89
Comparison
| Approach | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| DP Array | O(n) | O(n) | Understanding the pattern |
| Space Optimized | O(n) | O(1) | Large values of n |
Conclusion
The stair climbing problem follows the Fibonacci sequence where f(n) = f(n-1) + f(n-2). Use the DP approach for clarity and the space-optimized version for memory efficiency with large inputs.
