Skip to content

Commit c20e8e3

Browse files
committed
solve: climbing stairs
1 parent 2631e5f commit c20e8e3

File tree

2 files changed

+51
-30
lines changed

2 files changed

+51
-30
lines changed

climbing-stairs/sounmind.js

Lines changed: 0 additions & 30 deletions
This file was deleted.

climbing-stairs/sounmind.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class Solution:
2+
def climbStairs(self, n: int) -> int:
3+
"""
4+
Climbing Stairs Problem: You are climbing a staircase with n steps.
5+
Each time you can either climb 1 or 2 steps. How many distinct ways can you climb to the top?
6+
7+
This is essentially a Fibonacci sequence problem:
8+
- To reach step n, you can either:
9+
1. Take a single step from step (n-1)
10+
2. Take a double step from step (n-2)
11+
- Therefore, the total ways to reach step n = ways to reach (n-1) + ways to reach (n-2)
12+
13+
Time Complexity: O(n) - We need to calculate each step once
14+
Space Complexity: O(1) - We only store two previous values regardless of input size
15+
"""
16+
# Base cases: There's only 1 way to climb 1 step and 2 ways to climb 2 steps
17+
if n == 1:
18+
return 1
19+
if n == 2:
20+
return 2
21+
22+
# Initialize variables with base cases
23+
# For staircase with 1 step, there's only 1 way to climb
24+
ways_to_reach_n_minus_2 = 1
25+
26+
# For staircase with 2 steps, there are 2 ways to climb (1+1 or 2)
27+
ways_to_reach_n_minus_1 = 2
28+
29+
# Variable to store the current calculation
30+
ways_to_reach_current_step = 0
31+
32+
# Start calculating from step 3 up to step n
33+
for _ in range(3, n + 1):
34+
# To reach current step, we can either:
35+
# 1. Take a single step after reaching step (n-1)
36+
# 2. Take a double step after reaching step (n-2)
37+
# So the total ways = ways to reach (n-1) + ways to reach (n-2)
38+
ways_to_reach_current_step = (
39+
ways_to_reach_n_minus_1 + ways_to_reach_n_minus_2
40+
)
41+
42+
# Shift our window of calculations forward:
43+
# The previous (n-1) step now becomes the (n-2) step for the next iteration
44+
ways_to_reach_n_minus_2 = ways_to_reach_n_minus_1
45+
46+
# The current step calculation becomes the (n-1) step for the next iteration
47+
ways_to_reach_n_minus_1 = ways_to_reach_current_step
48+
49+
# After the final iteration, both ways_to_reach_n_minus_1 and ways_to_reach_current_step
50+
# have the same value (the answer for step n)
51+
return ways_to_reach_n_minus_1 # Could also return ways_to_reach_current_step

0 commit comments

Comments
 (0)