70. Climbing Stairs
Easy NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- 1-D Dynamic Programming
- Time
- O(N)
- Space
- O(1)
Standard Solution (C++)
SummaryGiven a staircase with n steps, count how many distinct ways you can reach the top by taking either 1 or 2 steps at a time.
Approach
- At each step i, you could have arrived from step i-1 (one step) or step i-2 (two steps), so the number of ways to reach step i is ways[i-1] + ways[i-2].
- This recurrence is identical to the Fibonacci sequence, with base cases ways[1] = 1 and ways[2] = 2.
- We only need the previous two values at each iteration, so we can use two variables instead of a full array, reducing space to O(1).
- Iterate from 3 to n, updating the rolling pair until we reach the answer.
#include <vector>
using namespace std;
class Solution {
public:
int climbStairs(int n) {
if (n <= 2) return n;
int prev2 = 1; // ways to reach step 1
int prev1 = 2; // ways to reach step 2
for (int i = 3; i <= n; ++i) {
int curr = prev1 + prev2; // Fibonacci-style recurrence
prev2 = prev1;
prev1 = curr;
}
return prev1;
}
};
Time O(n) Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
class Solution {
public:
int climbStairs(int n) {
if(n<2){
return n;
}
int prev1=2;
int prev2=1;
for(int i=3; i<=n; ++i){
int cur=prev1+prev2;
prev2=prev1;
prev1=cur;
}
return prev1;
}
};
// Time Complexity: O(N)
// Space Complexity: O(1) Time O(N) Space O(1)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.