Practice › Dynamic Programming
Climbing Stairs with 1, 2 or 3 Steps
Easy · Dynamic Programming · Asked at Amazon, Microsoft, TCS, Infosys, Wipro
You climb a staircase of n steps, taking 1, 2 or 3 steps at a time. Print the number of different ways to reach the top, modulo 10^9 + 7.
Input
A single integer n.
Output
The number of ways modulo 10^9 + 7.
Constraints
- 1 ≤ n ≤ 10^6
The last move was 1, 2 or 3 steps, so ways(n) = ways(n − 1) + ways(n − 2) + ways(n − 3), with ways(0) = 1. Keep the last three values.
Example 1
Input
3
Output
4
Example 2
Input
4
Output
7
Hints
- The last move onto step n was a 1-, 2- or 3-step.
- So ways(n) = ways(n − 1) + ways(n − 2) + ways(n − 3).
- ways(0) = 1: standing at the bottom is one way to "climb" zero steps.
Approach
Keep the last three values (a, b, c) = (ways(i − 3), ways(i − 2), ways(i − 1)), starting with (0, 0, 1) for i = 1 (treating negative step counts as 0 ways). Each step computes (a + b + c) mod 10^9 + 7 and shifts. After n steps, c is ways(n).
Complexity: O(n) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
const long long MOD = 1000000007LL;
int n;
cin >> n;
long long a = 0, b = 0, c = 1; // ways(-2), ways(-1), ways(0)
for (int i = 1; i <= n; i++) {
long long d = (a + b + c) % MOD;
a = b;
b = c;
c = d;
}
cout << c << "\n";
return 0;
}Python solution
MOD = 10**9 + 7
n = int(input())
a, b, c = 0, 0, 1
for _ in range(n):
a, b, c = b, c, (a + b + c) % MOD
print(c)Java solution
import java.util.*;
public class Main {
public static void main(String[] args) {
final long MOD = 1000000007L;
int n = new Scanner(System.in).nextInt();
long a = 0, b = 0, c = 1;
for (int i = 1; i <= n; i++) {
long d = (a + b + c) % MOD;
a = b;
b = c;
c = d;
}
System.out.println(c);
}
}Solve Climbing Stairs with 1, 2 or 3 Steps online · All practice problems