Climbing Stairs
Difficulty: Easy
You're climbing a staircase with n steps. Each move goes up 1 or 2 steps. Count the distinct ways to reach the top.
Examples
Input: n = 2
Output: 2
1 step + 1 step, or 2 steps.
Input: n = 3
Output: 3
1+1+1, 1+2, or 2+1.
Constraints
1 <= n <= 45
Approach
Your last move onto step n was either 1 step from n-1 or 2 steps from n-2. So the ways to reach step n are the ways to reach n-1 plus the ways to reach n-2, the same pattern as the Fibonacci sequence.
Plain recursion solves the same smaller subproblems again and again. Building up from the smallest steps and reusing each result avoids that.
Solutions
Brute Force — Plain Recursion
Directly recurse: the ways to reach n is ways(n-1) + ways(n-2). Correct, but recomputes the same subproblems exponentially many times.
function climbStairs(n) {
if (n <= 2) return n;
return climbStairs(n - 1) + climbStairs(n - 2);
}Time: O(2^n) · Space: O(n) — recursion depth
Optimal — Bottom-Up with Two Variables
Each step only needs the previous two results, so keep just the last two values and slide them forward.
function climbStairs(n) {
if (n <= 2) return n;
let prev2 = 1;
let prev1 = 2;
for (let i = 3; i <= n; i++) {
const current = prev1 + prev2;
prev2 = prev1;
prev1 = current;
}
return prev1;
}Time: O(n) · Space: O(1)