Full answer
Problem
You are at step 0 and want to reach step n. Each move climbs 1 or 2 steps. Return the number of distinct move sequences.
Example: n = 3 gives 3 (1+1+1, 1+2, 2+1); n = 5 gives 8.
Constraints: 0 <= n <= 90 here (results stay exact in Python; in 64-bit languages n = 92 is the overflow limit).
Brute force
Recursion straight from the definition: ways(n) = ways(n-1) + ways(n-2). The call tree doubles at each level, so it is O(2^n) (more precisely O(phi^n)), because ways(n-2) is recomputed inside ways(n-1).
Optimal approach
Bottom-up with two variables: start with a = ways(0) = 1 and b = ways(1) = 1, then repeat a, b = b, a + b until reaching n.
Generalization: for an allowed step set S, fill ways[0..n] with ways[0] = 1 and ways[i] = sum(ways[i - s] for s in S if s <= i).
Why it works
Every sequence that reaches step n ends with exactly one last move. Grouping sequences by that last move splits them into disjoint groups: those ending with a 1-step (each one is a way to reach n - 1) and those ending with a 2-step (a way to reach n - 2). Adding the group sizes counts each sequence once. Each value depends only on the two before it, so two variables are enough.
Complexity
O(n) time and O(1) space for the 1-or-2 version; O(n * |S|) time and O(n) space for a general step set. Matrix exponentiation of [[1,1],[1,0]] gives O(log n) arithmetic operations if n is huge.
Code
from functools import lru_cache
def climb(n):
"""Ways to climb n steps taking 1 or 2 at a time. ways(n) = ways(n-1) + ways(n-2). O(n), O(1)."""
a, b = 1, 1 # ways(0), ways(1)
for _ in range(n - 1):
a, b = b, a + b
return b if n >= 1 else 1
def climb_steps(n, steps):
"""General step set, e.g. {1, 3, 5}. O(n * len(steps)) time, O(n) space."""
ways = [1] + [0] * n
for i in range(1, n + 1):
ways[i] = sum(ways[i - s] for s in steps if s <= i)
return ways[n]
def brute(n):
"""Plain recursion: O(2^n). Only for small n."""
if n <= 1:
return 1
return brute(n - 1) + brute(n - 2)
@lru_cache(maxsize=None)
def memo(n):
return 1 if n <= 1 else memo(n - 1) + memo(n - 2)
if __name__ == "__main__":
assert [climb(n) for n in range(1, 7)] == [1, 2, 3, 5, 8, 13]
assert climb(0) == 1 # one way: do nothing
assert all(climb(n) == brute(n) == memo(n) == climb_steps(n, (1, 2)) for n in range(0, 22))
assert climb_steps(4, (1, 3)) == 3 # 1111, 13, 31
assert climb(90) == 4660046610375530309 # Python ints do not overflow
print("all tests passed")Save as b78_climbing_stairs.py and run python3 b78_climbing_stairs.py. It prints all tests passed (Python 3.13.5).
Edge cases
n = 0 (one way: no moves). n = 1 (one way). Large n (overflow in fixed-width languages; ask for a modulus). Step sets that include sizes larger than n.
Pattern
The basic DP template: define the state (ways to reach i), find the transition from the last decision, set base cases, and roll the table down to O(1) when only a few previous states matter. The same shape gives decode ways, tiling a 2 x n board, and min cost climbing stairs.
from functools import lru_cache
def climb(n):
"""Ways to climb n steps taking 1 or 2 at a time. ways(n) = ways(n-1) + ways(n-2). O(n), O(1)."""
a, b = 1, 1 # ways(0), ways(1)
for _ in range(n - 1):
a, b = b, a + b
return b if n >= 1 else 1
def climb_steps(n, steps):
"""General step set, e.g. {1, 3, 5}. O(n * len(steps)) time, O(n) space."""
ways = [1] + [0] * n
for i in range(1, n + 1):
ways[i] = sum(ways[i - s] for s in steps if s <= i)
return ways[n]
def brute(n):
"""Plain recursion: O(2^n). Only for small n."""
if n <= 1:
return 1
return brute(n - 1) + brute(n - 2)
@lru_cache(maxsize=None)
def memo(n):
return 1 if n <= 1 else memo(n - 1) + memo(n - 2)
if __name__ == "__main__":
assert [climb(n) for n in range(1, 7)] == [1, 2, 3, 5, 8, 13]
assert climb(0) == 1 # one way: do nothing
assert all(climb(n) == brute(n) == memo(n) == climb_steps(n, (1, 2)) for n in range(0, 22))
assert climb_steps(4, (1, 3)) == 3 # 1111, 13, 31
assert climb(90) == 4660046610375530309 # Python ints do not overflow
print("all tests passed")Two-variable loop, a general step-set table, memoized and plain recursion for comparison; all agree for n up to 21.
Complexity
Time: O(n). Space: O(1). General step sets cost O(n * |S|) time with an O(n) table.
By level
Fresher: Derives the recurrence from the last move and writes the bottom-up loop. Explains why the naive recursion repeats work.
Mid: Generalizes to any step set and to broken steps, and reduces space to O(1) where possible. Discusses overflow and modular answers.
Senior: Uses matrix exponentiation for very large n and explains the linear recurrence view. Connects the counting template to path counting on DAGs.
Key points
- Group sequences by their last move
- ways(n) = ways(n-1) + ways(n-2)
- Base cases ways(0) = ways(1) = 1
- Two variables replace the table
- Plain recursion is exponential
Common mistakes
- Wrong base case for n = 0
- Using plain recursion without memoization
- Off-by-one in the loop count
- Ignoring overflow in fixed-width languages
Follow-ups
- How would you compute this for n = 10^18 modulo a prime?
- What if some steps are broken and cannot be used?
- What if each step has a cost and you want the minimum cost?
Tips
- Derive the recurrence from the last move
- Show the exponential call tree briefly
- Roll the table to O(1) space
Evaluation rubric
- Correct recurrence and base cases
- O(n) solution
- Explains why recursion is slow
- Generalizes to other step sets