Count Distinct Staircase Climb Sequences
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
A staircase has n steps from the floor to the top landing. On every move, you may step up by either 1 stair or 2 stairs. Two climbs count as different whenever the ordered sequence of step sizes differs (for example, [1, 2] and [2, 1] are two distinct sequences).
def climb_stairs(n: int) -> int:
Compute and return the total number of distinct step sequences that land squarely on step n. Rather than relying on unmemoized branching recursion, design your implementation with dynamic programming (such as top-down memoization or bottom-up state iteration) so repeated subproblems are never recomputed from scratch.
Examples
Example 1
Input: n = 1
Output: 1
Explanation: Only [1] lands on step 1.
Example 2
Input: n = 4
Output: 5
Explanation: Five ordered step sequences add up to 4: [1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [2, 1, 1], and [2, 2].
Example 3
Input: n = 6
Output: 13
Explanation: Every valid sequence ending at step 6 finishes with either +1 from step 5 (8 sequences) or +2 from step 4 (5 sequences), giving 8 + 5 = 13 sequences in total.
Constraints
1 <= n <= 45
Step-by-step walkthrough
Understand what counts as a distinct sequence
Each climb is an ordered sequence of moves — where every move advances by
1or2stairs — whose move sizes sum ton. Order is significant:[1, 2](one stair, then two stairs) and[2, 1](two stairs, then one stair) count as two separate sequences.Listing the smallest values of
nby hand exposes the underlying pattern right away:n = 1 -> [1] (1 sequence) n = 2 -> [1+1], [2] (2 sequences) n = 3 -> [1+1+1], [1+2], [2+1] (3 sequences) n = 4 -> [1+1+1+1], [1+1+2], [1+2+1], [2+1+1], [2+2] (5 sequences)- Input: integer
n(1 <= n <= 45). - Output: exact integer count of distinct sequences ending at step
n.
- Input: integer
Derive the recurrence from the final move
How can we obtain
5forn = 4(Example 2) from smaller staircases without writing out every combination? Partition all sequences ending on stepnby their very last move:- Group A (final move was
+1): Immediately prior to that last 1-step, you stood on stepn - 1. Appending+1to each valid sequence ending atn - 1producesways(n - 1)valid sequences forn. - Group B (final move was
+2): Immediately prior to that last 2-step, you stood on stepn - 2. Appending+2to each valid sequence ending atn - 2producesways(n - 2)valid sequences forn.
Because no sequence can end with both
+1and+2, Group A and Group B are completely disjoint and together account for every valid climb:All sequences ending at step 4 (Example 2): Group A (sequences to 3, then +1): [1+1+1]+1, [1+2]+1, [2+1]+1 -> ways(3) = 3 Group B (sequences to 2, then +2): [1+1]+2, [2]+2 -> ways(2) = 2 ------------- Total ways(4) = ways(3) + ways(2) = 3 + 2 = 5For every
n >= 3:ways(1) = 1, ways(2) = 2, ways(n) = ways(n - 1) + ways(n - 2)- Group A (final move was
Why unmemoized recursion explodes: overlapping subproblems
Translating that formula directly into a plain recursive function works on tiny inputs, making it useful as a miniature test oracle:
def climb_stairs_naive(n: int) -> int: if n <= 2: return n return climb_stairs_naive(n - 1) + climb_stairs_naive(n - 2)Look at the call tree even for
n = 6(Example 3):ways(6) / \ ways(5) ways(4) <- ways(4) recomputed! / \ / \ ways(4) ways(3) ways(3) ways(2) <- ways(3) recomputed 3 times! / \ ways(3) ways(2)Every call splits into two recursive calls, solving the exact same smaller staircases (overlapping subproblems) again and again. At
n = 45,climb_stairs_naive(45)executes2,269,806,339calls — stalling for seconds — even though only45distinct valuesways(1)..ways(45)exist!Upgrade 1: top-down memoization
Dynamic programming eliminates redundant work in two classic ways: top-down memoization and bottom-up iteration.
Under top-down memoization, we keep the recursive helper
ways(step)and record each finished result inside a dictionarymemo. Wheneverways(step)is requested a second time, it returnsmemo[step]inO(1)time without branching further:def climb_stairs_memo(n: int) -> int: memo: dict[int, int] = {} def ways(step: int) -> int: if step <= 2: return step if step not in memo: memo[step] = ways(step - 1) + ways(step - 2) return memo[step] return ways(n)Each
stepin3..nis evaluated once, cutting runtime fromO(2^n)down toO(n). It usesO(n)memory formemoplusO(n)call-stack depth.Upgrade 2: bottom-up iteration in O(1) space
Notice that
ways(step)depends solely on the two preceding values:ways(step - 1)andways(step - 2). Evaluatingstep = 3, 4, ..., nin ascending order (bottom-up iteration) lets us drop both recursion and a full array in favor of a two-variable sliding window:Before step = i: ... [ ways(i - 2) ] [ ways(i - 1) ] ? ^ ^ ^ two_steps_back one_step_back current_ways = one_step_back + two_steps_back Advance window for step = i + 1: two_steps_back = one_step_back one_step_back = current_waysStoring the sum in
current_waysfirst prevents overwritingone_step_backbefore copying its prior value intotwo_steps_back.def climb_stairs(n: int) -> int: """Return the number of distinct sequences of 1- and 2-steps that sum to n.""" # Base cases: 1 step has 1 way ([1]); 2 steps has 2 ways ([1, 1] and [2]). if n <= 2: return n # Sliding DP state before starting step = 3: # two_steps_back stores ways(step - 2), initialized to ways(1) = 1 # one_step_back stores ways(step - 1), initialized to ways(2) = 2 two_steps_back = 1 one_step_back = 2 # Compute ways(3), ways(4), ..., ways(n) in bottom-up order. for step in range(3, n + 1): # Every climb to `step` finishes with either a 1-step from (step - 1) # or a 2-step from (step - 2); these two groups are disjoint. current_ways = one_step_back + two_steps_back # Advance the two-value window by one step for the next iteration. two_steps_back = one_step_back one_step_back = current_ways return one_step_backTrace Example 3 (n = 6)
Let's trace
climb_stairs(6)step by step (which also passes throughn = 4from Example 2):Start (after n <= 2 check): two_steps_back = 1 (ways(1)) one_step_back = 2 (ways(2)) step = 3: current_ways = 2 + 1 = 3 two_steps_back = 2, one_step_back = 3 step = 4 (Example 2 -> 5): current_ways = 3 + 2 = 5 two_steps_back = 3, one_step_back = 5 step = 5: current_ways = 5 + 3 = 8 two_steps_back = 5, one_step_back = 8 step = 6 (Example 3 -> 13): current_ways = 8 + 5 = 13 two_steps_back = 8, one_step_back = 13 Return one_step_back -> 13For Example 1 (
n = 1),if n <= 2: return nimmediately returns1. At the upper limitn = 45,43loop iterations return1,836,311,903in microseconds (which even fits inside a signed 32-bit integer, whose maximum is2,147,483,647).Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def climb_stairs(n: int) -> int: """Return the number of distinct sequences of 1- and 2-steps that sum to n.""" # Base cases: 1 step has 1 way ([1]); 2 steps has 2 ways ([1, 1] and [2]). if n <= 2: return n # Sliding DP state before starting step = 3: # two_steps_back stores ways(step - 2), initialized to ways(1) = 1 # one_step_back stores ways(step - 1), initialized to ways(2) = 2 two_steps_back = 1 one_step_back = 2 # Compute ways(3), ways(4), ..., ways(n) in bottom-up order. for step in range(3, n + 1): # Every climb to `step` finishes with either a 1-step from (step - 1) # or a 2-step from (step - 2); these two groups are disjoint. current_ways = one_step_back + two_steps_back # Advance the two-value window by one step for the next iteration. two_steps_back = one_step_back one_step_back = current_ways return one_step_back✅ Submit now — all tests should pass.
Intuition & how it works
Picture yourself arriving on step n and asking: "Which stair did my last stride start from?" Because each stride moves up by 1 or 2 stairs, you either stepped up +1 from stair n - 1 or stepped up +2 from stair n - 2. Those two endings never overlap, so the count of distinct climbs to stair n equals ways(n - 1) + ways(n - 2) — a recurrence relation (an equation expressing the answer for size n using answers for smaller sizes). Computing ways(1), ways(2), ways(3), ..., ways(n) in order while retaining only the latest two numbers is bottom-up dynamic programming (solving subproblems from smallest to largest so every subproblem is evaluated once and reused).
Why does calling ways(n - 1) + ways(n - 2) recursively without caching fail? Unmemoized recursion hits overlapping subproblems (identical smaller states like ways(n - 2) and ways(n - 3) get solved repeatedly across an exponentially branching call tree). By n = 45, plain recursion performs roughly 2.27 billion calls to compute just 45 distinct values!
Let's trace Example 2 (n = 4) and Example 3 (n = 6):
1. Base state: two_steps_back = 1 (ways(1)) and one_step_back = 2 (ways(2)).
2. step = 3: current_ways = 2 + 1 = 3; window advances to (2, 3).
3. step = 4: current_ways = 3 + 2 = 5 (matches Example 2); window advances to (3, 5).
4. step = 5: current_ways = 5 + 3 = 8; window advances to (5, 8).
5. step = 6: current_ways = 8 + 5 = 13 (matches Example 3); window advances to (8, 13) and returns 13.
Complexity
- Time:
O(n). Inputsn <= 2return inO(1)time; forn >= 3, the loop executesn - 2iterations, doing one integer addition and two variable assignments per iteration. (Unmemoized recursion, by contrast, takesO(phi^n)exponential time wherephi ≈ 1.618is the golden ratio.) - Space:
O(1)extra space. Only three integer variables (two_steps_back,one_step_back,current_ways) are stored regardless ofn, compared withO(n)space for a full DP table or memoization (caching recursive return values in a lookup map alongsideO(n)stack frames).
Edge cases
n = 1(Example 1): Handled before the loop byif n <= 2: return n, returning1([1]).n = 2: Returns2([1, 1]and[2]), which must not be confused withways(1) = 1.n = 45(maximum constraint): Produces1,836,311,903, which fits inside a signed 32-bit integer (max = 2,147,483,647);n = 46(2,971,215,073) would overflow signed 32-bit integers in C++ or Java, though Python ints have arbitrary precision.n = 0(if zero stairs were permitted): Combinatorially there is1empty move sequence for0stairs, matchingways(2) = ways(1) + ways(0) => 2 = 1 + 1; guardif n == 0: return 1if a caller can pass0.
Common mistakes
- Submitting plain unmemoized recursion: Finishes instantly on small samples (
n = 1, 4, 6) and then times out onn = 45. - Initializing
ways(2) = 1instead of2: Shifts the entire sequence down by one index (ways(4)becomes3instead of5). - Clobbering
one_step_backbefore updatingtwo_steps_back: Writingone_step_back = one_step_back + two_steps_backfollowed bytwo_steps_back = one_step_backcopies the new sum instead of the previousone_step_back. Computecurrent_waysfirst or use tuple assignment. - Using floating-point Binet's formula for general
n: Although rounding((1 + sqrt(5)) / 2) ** (n + 1) / sqrt(5)happens to match up ton = 45, IEEE-754 64-bit float precision drifts and produces wrong integers starting atn = 70. - Sharing a mutable default cache
def climb_stairs(n, memo={}): Prefer creatingmemoinside the function body so state does not leak across calls in general DP problems.
Alternative approaches
- Top-down memoization: Write the natural recursive helper
ways(step)and store computed entries in a local dictionarymemo(or@functools.lru_cache). It runs inO(n)time andO(n)space and is easy to adapt when state transitions jump unevenly. - Matrix exponentiation: Raising the
2 x 2transition matrix[[1, 1], [1, 0]]to powernvia exponentiation by squaring (repeatedly squaring the matrix to halve the exponent at each step) computesways(n)inO(log n)matrix multiplications. - Combinatorial binomial sum: Any sequence containing
kstrides of size2usesn - 2kstrides of size1, totalingn - kstrides. Choosing whichkpositions are 2-strides gives the binomial coefficientC(n - k, k)(the number of ways to pickkslots fromn - k), and summingC(n - k, k)overk = 0 .. n // 2equalsways(n).
Follow-up questions
- What are the practical trade-offs between top-down memoization and bottom-up iteration for this recurrence? Both cut runtime from
O(2^n)toO(n)by evaluating each stair count once. Top-down memoization mirrors the mathematical recurrence directly and visits only reachable subproblems when jump sizes are sparse, whereas bottom-up iteration avoids Python's recursion limit (RecursionErrornearn = 1000), removes function-call overhead, and compresses memory fromO(n)down toO(1). - How would you generalize the solution if allowed move sizes came from an arbitrary positive integer set S? Group sequences reaching stair
iby their final jumps in S:ways(i) = sum(ways(i - s) for s in S if s <= i), seeded withways(0) = 1. Computingways[0..n]bottom-up runs inO(n * len(S))time andO(n)space (orO(max(S))space using a circular array). - If n could be as large as 10^18 and only the answer modulo 10^9 + 7 were needed, how could you compute it in O(log n) time? An
O(n)loop cannot iterate10^18times, so write the state update in matrix form:[ways(i), ways(i - 1)]^T = [[1, 1], [1, 0]] * [ways(i - 1), ways(i - 2)]^T. Raising[[1, 1], [1, 0]]to the powernwith exponentiation by squaring and taking every intermediate product% (10^9 + 7)finishes inO(log n)(~60)2 x 2matrix multiplications andO(1)space. - How does the algorithm change if a given subset of stair indices is blocked and cannot be landed on? Store blocked indices in a hash set
blockedforO(1)membership checks, initializeways(0) = 1andways(1) = 0 if 1 in blocked else 1, and during the bottom-up sweep setcurrent_ways = 0wheneverstep in blocked(otherwiseone_step_back + two_steps_back). Zero sequences can pass through a blocked stair, while runtime staysO(n)and sliding-window space staysO(1).
Follow-up questions
- What are the practical trade-offs between top-down memoization and bottom-up iteration for this recurrence?
- How would you generalize the solution if allowed move sizes came from an arbitrary positive integer set S?
- If n could be as large as 10^18 and only the answer modulo 10^9 + 7 were needed, how could you compute it in O(log n) time?
- How does the algorithm change if a given subset of stair indices is blocked and cannot be landed on?
Similar questions
- Custom Hash Map with Put and Get
- Database Paradigms, Container Orchestration, and Python Performance
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance