Climbing Stairs solution explained

Climbing Stairs asks how many different sequences of 1-step and 2-step moves reach the top of an n-step staircase, and the answer follows from one observation: the last move was either a single step from n - 1 or a double step from n - 2, so ways(n) = ways(n - 1) + ways(n - 2). Computing that bottom-up with two variables takes O(n) time and O(1) space, and the counts are the Fibonacci numbers shifted by one.

By Published 8 min read

The problem in everyday terms

A staircase has n steps. Each move takes you up either one step or two. Count how many different move sequences land you exactly on the top step. Order matters: going one then two is different from going two then one. You only need the count, not the sequences themselves.

Small staircases, counted by hand for this page
Steps (n)WaysThe sequences
111
451+1+1+1, 2+1+1, 1+2+1, 1+1+2, 2+2
58Every 4-step way plus a final 1, and every 3-step way plus a final 2
6138 ways that end with a single step and 5 that end with a double
Small staircases, counted by hand for this page. Scroll sideways on a small screen.

Clarify the edges before coding: what should n = 0 return, if it is allowed at all? How large can n be, and will the count need to fit in a fixed-size integer or be reported modulo some number? Are the step sizes always 1 and 2? Each answer changes one line, and the size question decides whether you need big integers.

What this problem is really testing

Climbing Stairs is a gentle introduction to dynamic programming, and interviewers use it to see whether you can find a recurrence by thinking about the last decision rather than the first. Once you have the recurrence, the conversation moves to cost: why naive recursion explodes, how memoization fixes it, and how a bottom-up loop drops the memory to two numbers. Candidates who can walk that whole path in a few minutes are usually ready for harder DP problems.

Common variations

  • Moves of 1, 2 or 3 steps. The recurrence gains a third term: ways(n) = ways(n - 1) + ways(n - 2) + ways(n - 3). Keep three variables. For any set of allowed step sizes, sum over the set. Code is below.
  • Each step has a cost; find the cheapest climb. Replace the sum with a minimum: the cost to reach a step is its own cost plus the cheaper of the two ways to arrive.
  • Some steps are broken. Set the count for a broken step to zero and continue the same recurrence.
  • Report the count modulo a large prime. Take the remainder after each addition so numbers stay small.
  • Very large n. Raise the 2 × 2 matrix [[1, 1], [1, 0]] to a power by repeated squaring, which needs O(log n) multiplications.

Brute force: recurse on the last move

Translate the observation straight into code: the number of ways to reach step n is the number of ways to reach n - 1 plus the number of ways to reach n - 2, with one way to stand at the bottom and one way to reach the first step. It is correct, but each call spawns two more, and the same subproblems are solved over and over. The number of calls grows roughly like the answer itself, which is exponential in n.

def stair_ways_naive(n):
    if n <= 1:
        return 1
    return stair_ways_naive(n - 1) + stair_ways_naive(n - 2)
Direct recursion, exponential time. Fine for tiny n, hopeless by n = 40 or so.

Here n = 0 returns 1, meaning one way to climb nothing: make no moves. That convention keeps the recurrence clean. If the interviewer prefers 0 for n = 0, handle it separately before the recursion.

Fixing the repeats: memoization

There are only n + 1 distinct subproblems, so store each answer the first time it is computed. With a cache, every subproblem is solved once, and the time drops to O(n). The cache and the call stack each use O(n) memory, and on large n the recursion depth can still hit Python's limit.

from functools import lru_cache


@lru_cache(maxsize=None)
def stair_ways_memo(n):
    if n <= 1:
        return 1
    return stair_ways_memo(n - 1) + stair_ways_memo(n - 2)
Top-down with a cache, O(n) time and O(n) space.

Optimal approach: bottom-up with two numbers

Turn it around and build from the bottom. Each count needs only the two before it, so you never need the full table. Keep the count for the step two below and the step one below, and slide them forward n times. This uses O(n) time, O(1) extra space, and no recursion at all, which makes it the answer to finish on.

def stair_ways(n):
    two_below, one_below = 1, 1  # ways to stand at step 0 and step 1
    for _ in range(n - 1):
        two_below, one_below = one_below, two_below + one_below
    return one_below
Python: two rolling values, O(n) time and O(1) space. Python integers grow as needed.
function stairWays(n) {
  let twoBelow = 1;
  let oneBelow = 1;
  for (let i = 1; i < n; i++) {
    const next = twoBelow + oneBelow;
    twoBelow = oneBelow;
    oneBelow = next;
  }
  return oneBelow;
}
JavaScript: the same loop. Plain numbers stay exact up to n = 77; use BigInt past that.

Both versions return 1 for n = 0 and n = 1, since the loop body never runs. The counts are the Fibonacci numbers shifted by one position: ways(n) equals the (n + 1)th Fibonacci number if the sequence starts 1, 1, 2, 3. Mentioning that link is a nice touch, but derive the recurrence first, since that is what the interviewer is grading.

def stair_ways_with_sizes(n, sizes):
    ways = [0] * (n + 1)
    ways[0] = 1
    for step in range(1, n + 1):
        for s in sizes:
            if s <= step:
                ways[step] += ways[step - s]
    return ways[n]
Follow-up: any set of allowed step sizes, bottom-up table, O(n × k) for k sizes.

Complexity comparison

Each approach and what it costs
ApproachTimeExtra spaceNotes
Naive recursionExponential, about 1.6 to the nO(n) call stackRepeats the same subproblems
Memoized recursionO(n)O(n)Each subproblem solved once
Bottom-up tableO(n)O(n)Easy to extend to step costs or blocked steps
Two rolling variablesO(n)O(1)The expected final answer
Matrix power by squaringO(log n) multiplicationsO(1)Only matters for huge n, often with a modulus
Each approach and what it costs. Scroll sideways on a small screen.

Edge cases

  • n = 1: exactly one way.
  • n = 2: two ways, a quick check that the base cases are right.
  • n = 0: agree on 1 or 0 with the interviewer.
  • Large n in a language with fixed-width integers: the count passes the signed 32-bit limit by n = 46 and the signed 64-bit limit by n = 92.
  • Large n with recursion: the memoized version can exceed the default recursion depth even though its time is linear.

Where candidates trip

  • Writing the naive recursion and calling it O(n) because the recurrence has only two terms.
  • Off-by-one base cases, such as ways(2) = 1, which shifts every later answer.
  • Updating the two rolling variables in the wrong order and overwriting one before it is used.
  • Counting combinations instead of sequences, so 1+2 and 2+1 are treated as the same climb.
  • Ignoring overflow when n is large and the language uses fixed-width integers.

How to explain it out loud

Fictional example

Deriving the recurrence before writing code
Candidate
Think about the final move. To land on step n, I either came from n - 1 with a single step or from n - 2 with a double step. So the count for n is the count for n - 1 plus the count for n - 2.
Candidate
Recursing on that directly repeats work exponentially. Since each value only needs the two before it, I build up from the bottom with two variables, which is linear time and constant space.
Candidate
Checking small cases: one way for 1 step, two for 2, then 3, 5 and 8, and the five ways for 4 steps match what I can list by hand.

Problems with the same flavor

Maximum Subarray is the next step up in one-dimensional dynamic programming, where the carried value is a best sum rather than a count. Best Time to Buy and Sell Stock carries a single running minimum, and its multi-trade variants turn into small state machines built from recurrences like this one. All problems in the set are on the coding problems hub, and the software engineer interview questions guide covers the rest of a technical loop.

Studying with Natively

Dynamic programming clicks faster when you can test your recurrence against another explanation. In practice on a Mac or Windows PC, Natively can read a problem like this from a screenshot and suggest a recurrence, the bottom-up code and the edge cases. Since it transcribes your mock interviews, you can later reread whether you derived the recurrence or simply wrote it down. Learn more about an AI interview assistant.

Questions people ask

What is the recurrence for Climbing Stairs?

ways(n) = ways(n - 1) + ways(n - 2), because the last move onto step n is either a single step from n - 1 or a double step from n - 2. With ways(0) = ways(1) = 1, the counts are Fibonacci numbers shifted by one.

What is the time complexity of Climbing Stairs?

Plain recursion is exponential. Memoization or a bottom-up loop makes it O(n), and keeping only the last two counts brings the extra space down to O(1).

Is Climbing Stairs a dynamic programming problem?

Yes. It is one of the most common first examples: overlapping subproblems, a simple recurrence, and a table that shrinks to two variables.

How do you solve Climbing Stairs with 1, 2 or 3 steps at a time?

Add a third term: ways(n) = ways(n - 1) + ways(n - 2) + ways(n - 3), and keep three rolling values. For any set of step sizes, sum the counts for n minus each size.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP