Climbing Stairs
Easy
Topics
You are climbing a staircase with n steps. Each time you can climb 1 or 2 steps. In how many distinct ways can you reach the top?
Example 1
Each chip is one distinct way to climb 2 steps taking one or two at a time. Order counts as part of the identity, so
1+2 and 2+1 are two different climbs. The answer is how many there are, 2.Each chip is one climb, written as its sequence of step sizes.
Input: n = 2 Output: 2
Example 2
Input: n = 3 Output: 3
Constraints
- 1 <= n <= 45
Editorial — intuition, approach, complexity and pitfalls
Intuition
To land on step n your last move came from step n-1 (a single step) or step n-2 (a double step). So the number of ways to reach n is the sum of the ways to reach those two steps.
That is exactly the Fibonacci recurrence, computable in O(1) space.
Approach
- There is 1 way to be at the bottom and 1 way to reach step 1.
- Roll two counters forward:
next = a + b. - After
nsteps the counter holds ways(n).
Walkthrough
n = 4
steps: 1, 1, 2, 3, 5
ways(0)=1 ways(1)=1 ways(2)=2 ways(3)=3 ways(4)=5Complexity
- Time — O(n): a single loop to n.
- Space — O(1): only the last two counts are kept.
Common Pitfalls
- Keep the
n <= 2base case. The loop seedsprev, cur = 1, 2, which already assumes two steps exist, so without the guardn = 1returns 2 instead of 1. - This is Fibonacci offset by one, not Fibonacci. Lining the indices up wrong is the usual source of an answer that is right for every input except the smallest.
Full Solution — all languages
class Solution:
def climbStairs(self, n):
if n <= 2:
return n
prev, cur = 1, 2
for _ in range(3, n + 1):
prev, cur = cur, prev + cur
return curimport java.util.*;
class Solution {
public int climbStairs(int n) {
if (n <= 2) return n;
long prev = 1, cur = 2;
for (int i = 3; i <= n; i++) {
long next = prev + cur;
prev = cur;
cur = next;
}
return (int) cur;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int climbStairs(int n) {
if (n <= 2) return n;
long long prev = 1, cur = 2;
for (int i = 3; i <= n; i++) {
long long next = prev + cur;
prev = cur;
cur = next;
}
return (int)cur;
}
};/**
* @param {number} n
* @return {number}
*/ var climbStairs = function(n) {
if (n <= 2) return n;
let prev = 1, cur = 2;
for (let i = 3; i <= n; i++) {
const next = prev + cur;
prev = cur;
cur = next;
}
return cur;
};