Climbing Stairs
Climbing Stairs is a easy dynamic programming problem solved with the 1d dp pattern.
The best approach, optimal (rolling variables), runs in O(n) time and O(1) space.
Below are 3 approaches in Java, from recursion up.
Problem
You climb a staircase of n steps, taking 1 or 2 steps at a time. In how many distinct ways can you reach the top?
Examples
Example 1
- Input
n = 3- Output
3- Why
- 1+1+1, 1+2, 2+1.
Example 2
- Input
n = 5- Output
8
Constraints
1 <= n <= 45
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the Java code.
| Approach | Time | Space |
|---|---|---|
| Recursion | O(2ⁿ) | O(n) |
| Memoisation | O(n) | O(n) |
| Optimal (rolling variables) | O(n) | O(1) |
1Recursion
O(2ⁿ)O(n)ways(n) = ways(n - 1) + ways(n - 2), with ways(0) = ways(1) = 1.
- Base cases, then the two recursive calls.
class Solution {
public int climbStairs(int n) {
return n <= 1 ? 1 : climbStairs(n - 1) + climbStairs(n - 2);
}
}2Memoisation
O(n)O(n)Same recursion, caching each ways(i).
- memo[i]; return it when set.
class Solution {
private int[] memo;
public int climbStairs(int n) {
memo = new int[n + 1];
return ways(n);
}
private int ways(int i) {
if (i <= 1) return 1;
if (memo[i] != 0) return memo[i];
return memo[i] = ways(i - 1) + ways(i - 2);
}
}3Optimal (rolling variables)
O(n)O(1)Bottom-up with the last two answers only.
- prev2 = 1, prev1 = 1; for i in 2..n: cur = prev1 + prev2; shift.
class Solution {
public int climbStairs(int n) {
int prev2 = 1, prev1 = 1;
for (int i = 2; i <= n; i++) {
int cur = prev1 + prev2;
prev2 = prev1;
prev1 = cur;
}
return prev1;
}
}Edge cases to test
- n = 1
Hints
Hint 1
The last move was either 1 step (from n - 1) or 2 steps (from n - 2).
FAQ
What is the best time complexity for Climbing Stairs?
Optimal (rolling variables) runs in O(n) time and O(1) extra space.
Which pattern does Climbing Stairs use?
It is a dynamic programming problem that uses the 1d dp pattern. Other problems with the same pattern: Fibonacci Number, Min Cost Climbing Stairs (2 jumps), Minimal Cost (k jumps).
Is there a brute force solution for Climbing Stairs?
Yes. Recursion takes O(2ⁿ) time and O(n) space. ways(n) = ways(n - 1) + ways(n - 2), with ways(0) = ways(1) = 1.
Which edge cases should I test for Climbing Stairs?
n = 1.