15% off all plans & roadmaps Use code

See plans

Climbing Stairs

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

  • n is 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.
  • n is 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.

View on LeetCode

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.

Watch the pattern animation

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

  1. Return n directly when n is 1 or 2, since those are the base cases.
  2. Otherwise call the function for n - 1.
  3. Call the function for n - 2.
  4. 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) + 2
  • climb(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

TimeO(2^n)
SpaceO(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)

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

  1. Create a memo array of size n + 1, filled with 0 to mean not computed.
  2. Define a helper go(i) that returns i when i is 1 or 2.
  3. If memo[i] is already set, return it.
  4. Otherwise set memo[i] = go(i - 1) + go(i - 2).
  5. Return go(n).

Dry run

Trace n = 5 with the memo.

CallActionmemo after
go(5)needs go(4) firstall 0
go(4)needs go(3) firstall 0
go(3)go(2) + go(1) = 2 + 1 = 3memo[3] = 3
go(4)3 + go(2) = 3 + 2 = 5memo[4] = 5
go(5)5 + go(3), and go(3) is a memo hit, 3memo[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

TimeO(n)
SpaceO(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)
1D Array (Fibonacci Style) pattern infographic for Climbing Stairs

Solution pattern

1D Array (Fibonacci Style)

Part of Dynamic Programming (DP) Patterns

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

  1. Return n when n is 1 or 2.
  2. Set prev2 = 1 for stair 1 and prev1 = 2 for stair 2.
  3. Loop i from 3 to n inclusive.
  4. Compute current = prev1 + prev2.
  5. Slide the window: prev2 = prev1, then prev1 = current.
  6. After the loop, return prev1, which holds ways(n).

Dry run

Run n = 45. The window starts at prev2 = 1, prev1 = 2. Middle rows are skipped, but each follows the same rule.

icurrent = prev1 + prev2prev2 afterprev1 after
32 + 1 = 323
43 + 2 = 535
55 + 3 = 858
68 + 5 = 13813
713 + 8 = 211321
821 + 13 = 342134
............
44701408733 + 433494437 = 11349031707014087331134903170
451134903170 + 701408733 = 183631190311349031701836311903

The loop ends after i = 45, and prev1 is 1836311903, which matches the expected output.

Complexity

TimeO(n)
SpaceO(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 prev1

Common mistakes

  • Using if (n == 1) return 1 and then reading prev1 = 2 for stair 2 without a guard. For n = 1 the code returns the wrong value or reads a missing index. Guard with if n <= 2: return n before the loop.
  • Looping for i in range(3, n) instead of range(3, n + 1). The loop stops one stair early and returns ways(n-1). In Python the upper bound is exclusive, so write n + 1.
  • Updating the window in the wrong order, for example prev1 = current before prev2 = prev1. That overwrites prev1 and both variables end up equal to current. Assign prev2 = prev1 first, 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 why ways(2) = ways(1) + ways(0) works. If you start from index 0, seed it with 1, not 0.
  • Allocating dp = [0] * n and writing dp[n]. The array needs n + 1 slots because stairs are numbered 1 through n. Size it n + 1 or 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

Practise it