15% off all plans & roadmaps Use code
See plansClimbing Stairs
- LeetCode 70
- Easy
- Dynamic Programming (DP) Patterns
- 1D Array (Fibonacci Style)
Updated
TL;DR: Count the ways to climb n stairs taking 1 or 2 steps at a time. The count for step i is the count for step i-1 plus the count for step i-2, so you can build it up with two variables in O(n) time and O(1) space.
Problem
You are climbing a staircase that has n steps to reach the top.
On each move you climb either 1 or 2 steps. Return the number of distinct ways you can reach the top.
Example 1
Input: n = 2 Output: 2 Explanation: There are two ways to reach the top. 1. 1 step + 1 step 2. 2 steps
Example 2
Input: n = 3 Output: 3 Explanation: There are three ways to reach the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step
Constraints
1 <= n <= 45
Constraints that matter
nis at most 45, so the answer is at most 1836311903. That is below 2^31 - 1 = 2147483647, so a 32-bit int never overflows and you need no big-number handling.- A recursion that calls itself twice per level makes about 2^n calls. At n = 45 that is billions of calls, so plain recursion is too slow and you need to reuse results.
nis at least 1, so you never have to handle zero stairs. The base cases for n = 1 and n = 2 are enough to start the recurrence.- The input is a single integer, so the real cost is the loop or recursion depth, not input size. An O(n) loop of at most 45 iterations is trivial.
Hints
Hint 1
This is dynamic programming on a one-dimensional sequence.
Hint 2
Translate the recurrence directly into a function.
Solution
Intuition
This is dynamic programming on a one-dimensional sequence. The question asks you to count paths, and every path ends with one last move. That last move is either a 1-step from stair i-1 or a 2-step from stair i-2. No other final move exists.
Picture a two-cell sliding window on a row of stairs: each new stair's count is the sum of the two cells, and then the window moves forward one stair, dropping the oldest cell. The two variables are that window, and the skipped older stairs are exactly the values you no longer need.
Those two groups of paths never overlap, because the last move differs. Every path to stair i falls into exactly one group. So ways(i) = ways(i-1) + ways(i-2). Whenever a count splits cleanly by the last decision, you can write a recurrence like this.
The recurrence has two base cases. There is 1 way to reach stair 1 and 2 ways to reach stair 2. After that, each value depends only on the two before it, which is the Fibonacci pattern shifted by one: ways(n) equals the (n+1)th Fibonacci number.
The clue that points to DP is overlap. ways(5) needs ways(4) and ways(3), and ways(4) also needs ways(3). Once you compute a value, store it or roll it forward instead of rebuilding it. Because only two earlier values matter, you can keep two variables and drop the array.
Worked example
Input: n = 45 Output: 1836311903 Explanation: The count for each step is the sum of the counts for the two steps below it. Starting from 1 way for step 1 and 2 ways for step 2, the counts run 3, 5, 8, 13, and so on. At step 45 the count is 1836311903, which still fits in a 32-bit signed integer.
Approach 1: Brute force recursion
Translate the recurrence directly into a function. climb(n) returns climb(n-1) + climb(n-2), with climb(1) = 1 and climb(2) = 2. Each call explores both choices for the last move, so it enumerates every path through the staircase by splitting.
This is correct and short. It is also the version you write first in an interview, and it is the right place to start so you can point at the waste.
Steps
- Return
ndirectly whennis 1 or 2, since those are the base cases. - Otherwise call the function for
n - 1. - Call the function for
n - 2. - Return the sum of the two results.
Dry run
Trace climb(5) as a small case.
climb(5) = climb(4) + climb(3)climb(4) = climb(3) + climb(2) = climb(3) + 2climb(3) = climb(2) + climb(1) = 2 + 1 = 3
So climb(4) = 3 + 2 = 5, and climb(5) = 5 + 3 = 8. Notice that climb(3) was computed twice, once under climb(5) and once under climb(4).
For n = 45 the same rule gives 1836311903 as the final sum. Reaching it takes about 2.27 billion calls, because every leaf of the call tree contributes exactly 1 or 2 to the total and the tree has Fibonacci-many leaves.
Complexity
| Time | O(2^n) |
|---|---|
| Space | O(n) |
Here n is the number of stairs. Each call with n above 2 makes two calls, and the call tree has depth up to n. The number of leaves equals a Fibonacci number, which grows like 1.618^n, so the tree has at most 2^n nodes and the time is O(2^n). Only one root-to-leaf path is on the call stack at a time, so the extra space is the depth, O(n).
PythonTested in our runner
from typing import List, Optional
from functools import lru_cache
class Solution:
def climbStairs(self, n: int) -> int:
# Same recurrence as brute force, with memoization so each n is computed once
@lru_cache(maxsize=None)
def climb(k: int) -> int:
# Base cases: 1 way for one stair, 2 ways for two stairs
if k <= 2:
return k
# The last move was a 1-step or a 2-step
return climb(k - 1) + climb(k - 2)
return climb(n)JavaTested in our runner
class Solution {
public int climbStairs(int n) {
// Base cases: 1 way for one stair, 2 ways for two stairs
if (n <= 2) {
return n;
}
// The last move was a 1-step or a 2-step
return climbStairs(n - 1) + climbStairs(n - 2);
}
}C++Tested in our runner
class Solution {
public:
int climbStairs(int n) {
// Base cases: 1 way for one stair, 2 ways for two stairs
if (n <= 2) {
return n;
}
// The last move was a 1-step or a 2-step
return climbStairs(n - 1) + climbStairs(n - 2);
}
};JavaScriptTested in our runner
/**
* @param {number} n
* @return {number}
*/
var climbStairs = function(n) {
// Cache results so each subproblem is computed only once
const memo = new Map();
const climb = (k) => {
// Base cases: 1 way for one stair, 2 ways for two stairs
if (k <= 2) {
return k;
}
if (memo.has(k)) {
return memo.get(k);
}
// The last move was a 1-step or a 2-step
const res = climb(k - 1) + climb(k - 2);
memo.set(k, res);
return res;
};
return climb(n);
};GoTested in our runner
func climbStairs(n int) int {
// Base cases: 1 way for one stair, 2 ways for two stairs
if n <= 2 {
return n
}
// The last move was a 1-step or a 2-step
return climbStairs(n-1) + climbStairs(n-2)
}C#Tested in our runner
public class Solution {
public int climbStairs(int n) {
// Base cases: 1 way for one stair, 2 ways for two stairs
if (n <= 2) {
return n;
}
// The last move was a 1-step or a 2-step
return climbStairs(n - 1) + climbStairs(n - 2);
}
}Approach 2: Top-down memoization
What's slow: the brute force solves the same subproblem again and again. In the climb(5) trace, climb(3) ran twice. At larger n, climb(10) is recomputed dozens of times, and the repeats multiply down the tree.
The insight that fixes it: the answer for a given stair never changes. Compute it once, store it in an array indexed by stair number, and return the stored value on every later call. The recursion stays the same, but each stair is now solved only once.
Steps
- Create a memo array of size
n + 1, filled with 0 to mean not computed. - Define a helper
go(i)that returnsiwheniis 1 or 2. - If
memo[i]is already set, return it. - Otherwise set
memo[i] = go(i - 1) + go(i - 2). - Return
go(n).
Dry run
Trace n = 5 with the memo.
| Call | Action | memo after |
|---|---|---|
| go(5) | needs go(4) first | all 0 |
| go(4) | needs go(3) first | all 0 |
| go(3) | go(2) + go(1) = 2 + 1 = 3 | memo[3] = 3 |
| go(4) | 3 + go(2) = 3 + 2 = 5 | memo[4] = 5 |
| go(5) | 5 + go(3), and go(3) is a memo hit, 3 | memo[5] = 8 |
The second go(3) returns immediately from the memo. For n = 45 the same pattern fills memo[3] through memo[45] once each, and the last value is 1836311903.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Here n is the number of stairs. Each index from 3 to n is computed once, because after the first computation every call to it is a constant-time lookup. Each computation does one addition, so the total time is O(n). The memo array holds n + 1 integers and the recursion goes n levels deep, so the space is O(n).
PythonTested in our runner
class Solution:
def climbStairs(self, n: int) -> int:
memo = [0] * (n + 1)
def go(i: int) -> int:
if i <= 2:
return i
if memo[i]:
return memo[i] # already solved
memo[i] = go(i - 1) + go(i - 2)
return memo[i]
return go(n)JavaTested in our runner
import java.util.*;
class Solution {
public int climbStairs(int n) {
int[] memo = new int[n + 1];
return go(n, memo);
}
private int go(int i, int[] memo) {
if (i <= 2) {
return i;
}
if (memo[i] != 0) {
return memo[i]; // already solved
}
memo[i] = go(i - 1, memo) + go(i - 2, memo);
return memo[i];
}
};C++Tested in our runner
#include <vector>
class Solution {
public:
int climbStairs(int n) {
std::vector<int> memo(n + 1, 0);
return go(n, memo);
}
private:
int go(int i, std::vector<int>& memo) {
if (i <= 2) {
return i;
}
if (memo[i] != 0) {
return memo[i]; // already solved
}
memo[i] = go(i - 1, memo) + go(i - 2, memo);
return memo[i];
}
};JavaScriptTested in our runner
/**
* @param {number} n
* @return {number}
*/
var climbStairs = function(n) {
const memo = new Array(n + 1).fill(0);
const go = (i) => {
if (i <= 2) {
return i;
}
if (memo[i] !== 0) {
return memo[i]; // already solved
}
memo[i] = go(i - 1) + go(i - 2);
return memo[i];
};
return go(n);
};GoTested in our runner
func climbStairs(n int) int {
memo := make([]int, n+1)
var do func(i int) int
do = func(i int) int {
if i <= 2 {
return i
}
if memo[i] != 0 {
return memo[i] // already solved
}
memo[i] = do(i-1) + do(i-2)
return memo[i]
}
return do(n)
}C#Tested in our runner
public class Solution {
public int climbStairs(int n) {
int[] memo = new int[n + 1];
return Go(n, memo);
}
private int Go(int i, int[] memo) {
if (i <= 2) {
return i;
}
if (memo[i] != 0) {
return memo[i]; // already solved
}
memo[i] = Go(i - 1, memo) + Go(i - 2, memo);
return memo[i];
}
}
Solution pattern
1D Array (Fibonacci Style)
Approach 3: Bottom-up with two variablesOptimal1D Array (Fibonacci Style)
What's slow: memoization fixes the time, but it still stores n + 1 values and recurses n levels deep. Every stair below the previous two is dead weight once you have moved past it, because ways(i) reads only ways(i-1) and ways(i-2).
The insight that fixes it: walk upward from stair 3 and keep only the last two values in two variables. At each stair compute the sum, then slide the window by one. This removes the array and the recursion, so the space drops to O(1).
Why it is correct. Every path to stair i ends with either a 1-step or a 2-step, and those two groups never overlap, so the count for i is exactly the sum of the counts for i-1 and i-2. The loop keeps the invariant that prev2 and prev1 hold ways(i-2) and ways(i-1) at the start of each iteration. Since the recurrence only reads those two values, dropping older entries never loses information needed for a later answer.
Steps
- Return
nwhennis 1 or 2. - Set
prev2 = 1for stair 1 andprev1 = 2for stair 2. - Loop
ifrom 3 toninclusive. - Compute
current = prev1 + prev2. - Slide the window:
prev2 = prev1, thenprev1 = current. - After the loop, return
prev1, which holdsways(n).
Dry run
Run n = 45. The window starts at prev2 = 1, prev1 = 2. Middle rows are skipped, but each follows the same rule.
| i | current = prev1 + prev2 | prev2 after | prev1 after |
|---|---|---|---|
| 3 | 2 + 1 = 3 | 2 | 3 |
| 4 | 3 + 2 = 5 | 3 | 5 |
| 5 | 5 + 3 = 8 | 5 | 8 |
| 6 | 8 + 5 = 13 | 8 | 13 |
| 7 | 13 + 8 = 21 | 13 | 21 |
| 8 | 21 + 13 = 34 | 21 | 34 |
| ... | ... | ... | ... |
| 44 | 701408733 + 433494437 = 1134903170 | 701408733 | 1134903170 |
| 45 | 1134903170 + 701408733 = 1836311903 | 1134903170 | 1836311903 |
The loop ends after i = 45, and prev1 is 1836311903, which matches the expected output.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Here n is the number of stairs. The loop runs n - 2 times for n of at least 3, and each pass does one addition and two assignments, so the time is O(n). The code holds three integers (prev2, prev1, current) no matter how large n is, so the space is O(1). Correctness follows by induction: the window holds ways(i-2) and ways(i-1) at the start of pass i, and the sum is ways(i).
PythonTested in our runner
class Solution:
def climbStairs(self, n: int) -> int:
if n <= 2:
return n
prev2, prev1 = 1, 2 # ways to reach stair 1 and stair 2
for _ in range(3, n + 1):
current = prev1 + prev2
prev2 = prev1 # slide the window
prev1 = current
return prev1JavaTested in our runner
class Solution {
public int climbStairs(int n) {
if (n <= 2) {
return n;
}
int prev2 = 1; // ways to reach stair 1
int prev1 = 2; // ways to reach stair 2
for (int i = 3; i <= n; i++) {
int current = prev1 + prev2;
prev2 = prev1; // slide the window
prev1 = current;
}
return prev1;
}
}C++Tested in our runner
class Solution {
public:
int climbStairs(int n) {
if (n <= 2) {
return n;
}
int prev2 = 1; // ways to reach stair 1
int prev1 = 2; // ways to reach stair 2
for (int i = 3; i <= n; i++) {
int current = prev1 + prev2;
prev2 = prev1; // slide the window
prev1 = current;
}
return prev1;
}
};JavaScriptTested in our runner
/**
* @param {number} n
* @return {number}
*/
var climbStairs = function(n) {
if (n <= 2) {
return n;
}
let prev2 = 1; // ways to reach stair 1
let prev1 = 2; // ways to reach stair 2
for (let i = 3; i <= n; i++) {
const current = prev1 + prev2;
prev2 = prev1; // slide the window
prev1 = current;
}
return prev1;
};GoTested in our runner
func climbStairs(n int) int {
if n <= 2 {
return n
}
prev2, prev1 := 1, 2 // ways to reach stair 1 and stair 2
for i := 3; i <= n; i++ {
current := prev1 + prev2
prev2 = prev1 // slide the window
prev1 = current
}
return prev1
}C#Tested in our runner
public class Solution {
public int climbStairs(int n) {
if (n <= 2) {
return n;
}
int prev2 = 1; // ways to reach stair 1
int prev1 = 2; // ways to reach stair 2
for (int i = 3; i <= n; i++) {
int current = prev1 + prev2;
prev2 = prev1; // slide the window
prev1 = current;
}
return prev1;
}
}Common mistakes
- Using
if (n == 1) return 1and then readingprev1 = 2for stair 2 without a guard. For n = 1 the code returns the wrong value or reads a missing index. Guard withif n <= 2: return nbefore the loop. - Looping
for i in range(3, n)instead ofrange(3, n + 1). The loop stops one stair early and returnsways(n-1). In Python the upper bound is exclusive, so writen + 1. - Updating the window in the wrong order, for example
prev1 = currentbeforeprev2 = prev1. That overwritesprev1and both variables end up equal tocurrent. Assignprev2 = prev1first, or use a tuple swap. - Writing the plain recursion
climb(n-1) + climb(n-2)with no cache. It is correct but makes billions of calls at n = 45 and times out. Add a memo array or switch to the loop. - Setting the base cases to
ways(0) = 0. A zero-stair staircase has exactly one way, doing nothing, which is whyways(2) = ways(1) + ways(0)works. If you start from index 0, seed it with 1, not 0. - Allocating
dp = [0] * nand writingdp[n]. The array needsn + 1slots because stairs are numbered 1 through n. Size itn + 1or use the two-variable version.
Edge cases
- n = 1: the only move is one step, so the answer is 1. The early return handles it before the loop.
- n = 2: either 1+1 or a single 2, so the answer is 2. The early return handles it.
- n = 3: the loop runs once and returns 3 (1+1+1, 1+2, 2+1).
- n = 4: the answer is 5, which checks that the recurrence adds the right two values.
- n = 45, the maximum: the answer is 1836311903. It fits in a signed 32-bit int, so no overflow handling is needed in Java, C++ or C#.
Follow-ups interviewers ask
- What if n were as large as 10^9 and you had to return the answer modulo a prime?
- The O(n) loop is too slow. Write the recurrence as a 2 by 2 matrix [[1,1],[1,0]] and raise it to the power n using repeated squaring. That takes O(log n) multiplications. Fast doubling for Fibonacci reaches the same bound with fewer operations. Apply the modulus after every multiplication.
- What if you may climb any number of steps from 1 to k?
- The recurrence becomes ways(i) = ways(i-1) + ... + ways(i-k). Computing each sum from scratch costs O(n * k). Keep a running window sum instead: add ways(i-1) and subtract ways(i-k-1). That gives O(n) time, with O(k) space if you store a circular buffer or O(n) if you keep the whole array.
- What if some stairs are broken and you cannot land on them?
- Keep the same DP but set ways(i) = 0 for every broken stair i. A zero contributes nothing to later sums, so paths through broken stairs are never counted. The time stays O(n), and you only need a lookup for whether a stair is broken, such as a boolean array or a set.
Climbing Stairs FAQ
What is the time complexity of Climbing Stairs?
The optimal solution runs in O(n) time and O(1) space, where n is the number of stairs. The plain recursion takes O(2^n) time because it recomputes the same subproblems. Memoization brings the time to O(n) but uses O(n) space.
Why use dynamic programming for Climbing Stairs?
The count for stair i depends only on the counts for stairs i-1 and i-2, and those same values are needed by many larger stairs. That is overlapping subproblems with a simple recurrence. DP computes each value once instead of re-deriving it in an exponential call tree.
Is Climbing Stairs the same as the Fibonacci sequence?
Almost. With ways(1) = 1 and ways(2) = 2, you get ways(n) = F(n+1), where F(1) = F(2) = 1. For n = 45 that is F(46) = 1836311903. The shift comes from the base cases, not the recurrence.
Can Climbing Stairs be solved in O(1) extra space?
Yes. The recurrence reads only the last two values, so two integer variables replace the whole array. The loop still runs n times, so the time is O(n) and the extra space is constant.
Can Climbing Stairs be solved faster than O(n)?
Yes, in theory. Matrix exponentiation or fast doubling computes the answer in O(log n) multiplications. The closed form with the golden ratio also works, but floating-point error makes it unsafe for exact answers. With n at most 45, the plain O(n) loop is the right choice in an interview.
How do I write Climbing Stairs in Python or Java without overflow?
Python integers have no fixed size, so overflow is not a concern. In Java and C#, the maximum answer 1836311903 is below 2147483647, so a plain int is safe within the constraint n <= 45. For larger n you would switch to long or apply a modulus.
Asked at
See which companies ask this — Pro
Related problems
- Min Cost Climbing Stairs · same technique: 1D Array (Fibonacci Style)
- N-th Tribonacci Number · same technique: 1D Array (Fibonacci Style)
- Fibonacci Number · same technique: 1D Array (Fibonacci Style)
- House Robber · same technique: 1D Array (Fibonacci Style)
- Decode Ways · same technique: 1D Array (Fibonacci Style)
- Best Time to Buy and Sell Stock · same pattern: Dynamic Programming (DP) Patterns
- Coin Change · same pattern: Dynamic Programming (DP) Patterns
- Maximum Subarray · same pattern: Dynamic Programming (DP) Patterns
- Word Break · same pattern: Dynamic Programming (DP) Patterns
- Longest Increasing Subsequence · same pattern: Dynamic Programming (DP) Patterns