Climbing Stairs - Problem
Imagine you're at the bottom of a staircase with exactly n steps leading to the top. You want to reach the top, but there's a catch - you can only take 1 step or 2 steps at a time!
Your goal is to determine how many different ways you can climb to the top of the staircase.
Example: If there are 3 steps, you could climb them as:
- 1 step + 1 step + 1 step
- 1 step + 2 steps
- 2 steps + 1 step
That's 3 different ways total!
Input: An integer n representing the number of steps
Output: An integer representing the number of distinct ways to reach the top
Input & Output
example_1.py โ Basic case with 2 steps
$
Input:
n = 2
โบ
Output:
2
๐ก Note:
There are two ways to climb to the top: 1. Take 1 step + 1 step, 2. Take 2 steps at once
example_2.py โ Medium case with 3 steps
$
Input:
n = 3
โบ
Output:
3
๐ก Note:
There are three ways: 1. Take 1+1+1 steps, 2. Take 1+2 steps, 3. Take 2+1 steps
example_3.py โ Edge case with 1 step
$
Input:
n = 1
โบ
Output:
1
๐ก Note:
There is only one way to reach the top: take 1 step
Visualization
Tap to expand
Understanding the Visualization
1
Recognize the Pattern
To reach step n, you must come from either step (n-1) or step (n-2)
2
Count Combinations
Total ways to reach step n = ways to reach (n-1) + ways to reach (n-2)
3
Fibonacci Connection
This creates the famous Fibonacci sequence: 1, 1, 2, 3, 5, 8, 13...
Key Takeaway
๐ฏ Key Insight: The climbing stairs problem is the Fibonacci sequence in disguise! Each step count equals the sum of the two previous step counts, leading to an elegant O(n) time, O(1) space solution.
Time & Space Complexity
Time Complexity
O(n)
Single loop from 2 to n, each iteration takes constant time
โ Linear Growth
Space Complexity
O(1)
Only uses two variables regardless of input size
โ Linear Space
Constraints
- 1 โค n โค 45
- Integer overflow: The answer will fit in a 32-bit integer
- The problem is guaranteed to have a valid solution
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code