Climbing Stairs
The problem
Given an integer n, there is a staircase with n steps, starting from the 0th step.
Determine the number of unique ways to reach the nth step, given that each move can be either 1 or 2 steps at a time.
Input: n = 2 Output: 2 Explanation: There are 2 unique ways to climb to the 2nd step:
- 1 step + 1 step
- 2 steps
Input: n = 3 Output: 3 Explanation: There are 3 unique ways to climb to the 3rd step:
- 1 step + 1 step + 1 step
- 2 steps + 1 step
- 1 step + 2 steps
Input: n = 1
- 1 <= n <= 45
cpp
class Solution {
public:
int climbStairs(int n) {
}
};java
class Solution {
public int climbStairs(int n) {
}
}python
class Solution:
def climbStairs(self, n):javascript
class Solution {
climbStairs(n) {
}
}csharp
public class Solution {
public int climbStairs(int n) {
}
}go
func climbStairs(n int) int {
}Stuck? Show a way to structure it+
- 01Define ways(i) as the ways to reach step i.
- 02Use ways(i)=ways(i-1)+ways(i-2).
- 03Initialize the first two reachable states.
- 04Keep only the previous two values.
Reference answer
Then expect these follow-ups
What changes if steps of size 1, 2, or 3 are allowed?
Tests: generalizing recurrence
How would you compute a huge n modulo M?
Tests: modular arithmetic
Free to read · better with Enzo
Practice this out loud with Enzo
Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.
Next question
- Calculate the trapped rainwater between bars in a given array.
- Find a triplet in an array with a given sum.
- Print all combinations of numbers from 1 to n that sum to n.
- Find the number of rotations in a circularly sorted array.
- Find all permutations of a given string.
- Check if two given binary trees are identical.