Climbing Stairs
Easy · Dynamic programming
Jump to codeA staircase has n ≥ 1 steps. You can climb one or two steps at a time. Count the different ordered sequences of moves that reach the top exactly.
Examples
Example 1
n = 2
Output: 2
Example 2
n = 3
Output: 3
Constraints
- 1 <= n <= 30
Need a hint?
The final move comes from one or two steps below.
Real dynamic programming interview questions
Questions on the same topic that candidates reported from real company interviews. Some company questions are locked and open with Premium or XP.
- Minimize Branch Merge ConflictsAmazon
- Count Distinct Hat Assignments and Maximize Hat PointsRoblox
- Find and Count Maximum-Score Grid PathsOpenAI
Solution approach
Define ways(0) = 1 and ways(1) = 1. For each higher step, ways(i) = ways(i−1) + ways(i−2). Keep only the previous two counts. Treating zero steps as one empty sequence makes the recurrence consistent.
Complexity
O(n) time and O(1) auxiliary space under fixed-width arithmetic.
Python reference solution
def climbStairs(n):
before, current = 1, 1
for _ in range(2, n + 1):
before, current = current, before + current
return current
JavaScript solution
function climbStairs(n) {
let before = 1, current = 1;
for (let step = 2; step <= n; step++) [before, current] = [current, before + current];
return current;
}
Java solution
import java.util.*;
class Solution {
public int climbStairs(int n) {
int before = 1, current = 1;
for (int step = 2; step <= n; step++) {
int next = before + current;
before = current; current = next;
}
return current;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int climbStairs(int n) {
int before = 1, current = 1;
for (int step = 2; step <= n; step++) {
int next = before + current;
before = current; current = next;
}
return current;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 7 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[ 2 ]
2
[ 3 ]
3
[ 1 ]
1
[ 4 ]
5
[ 5 ]
8
Drafts are saved per language in this browser when storage is available.