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

  1. Understand what counts as a distinct sequence

    Each climb is an ordered sequence of moves — where every move advances by 1 or 2 stairs — whose move sizes sum to n. 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 n by 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.
  2. Derive the recurrence from the final move

    How can we obtain 5 for n = 4 (Example 2) from smaller staircases without writing out every combination? Partition all sequences ending on step n by their very last move:

    • Group A (final move was +1): Immediately prior to that last 1-step, you stood on step n - 1. Appending +1 to each valid sequence ending at n - 1 produces ways(n - 1) valid sequences for n.
    • Group B (final move was +2): Immediately prior to that last 2-step, you stood on step n - 2. Appending +2 to each valid sequence ending at n - 2 produces ways(n - 2) valid sequences for n.

    Because no sequence can end with both +1 and +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 = 5
    

    For every n >= 3:

    ways(1) = 1,   ways(2) = 2,   ways(n) = ways(n - 1) + ways(n - 2)
    
  3. 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) executes 2,269,806,339 calls — stalling for seconds — even though only 45 distinct values ways(1)..ways(45) exist!

  4. 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 dictionary memo. Whenever ways(step) is requested a second time, it returns memo[step] in O(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 step in 3..n is evaluated once, cutting runtime from O(2^n) down to O(n). It uses O(n) memory for memo plus O(n) call-stack depth.

  5. Upgrade 2: bottom-up iteration in O(1) space

    Notice that ways(step) depends solely on the two preceding values: ways(step - 1) and ways(step - 2). Evaluating step = 3, 4, ..., n in 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_ways
    

    Storing the sum in current_ways first prevents overwriting one_step_back before copying its prior value into two_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_back
    
  6. Trace Example 3 (n = 6)

    Let's trace climb_stairs(6) step by step (which also passes through n = 4 from 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 -> 13
    

    For Example 1 (n = 1), if n <= 2: return n immediately returns 1. At the upper limit n = 45, 43 loop iterations return 1,836,311,903 in microseconds (which even fits inside a signed 32-bit integer, whose maximum is 2,147,483,647).

  7. 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). Inputs n <= 2 return in O(1) time; for n >= 3, the loop executes n - 2 iterations, doing one integer addition and two variable assignments per iteration. (Unmemoized recursion, by contrast, takes O(phi^n) exponential time where phi ≈ 1.618 is the golden ratio.)
  • Space: O(1) extra space. Only three integer variables (two_steps_back, one_step_back, current_ways) are stored regardless of n, compared with O(n) space for a full DP table or memoization (caching recursive return values in a lookup map alongside O(n) stack frames).

Edge cases

  • n = 1 (Example 1): Handled before the loop by if n <= 2: return n, returning 1 ([1]).
  • n = 2: Returns 2 ([1, 1] and [2]), which must not be confused with ways(1) = 1.
  • n = 45 (maximum constraint): Produces 1,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 is 1 empty move sequence for 0 stairs, matching ways(2) = ways(1) + ways(0) => 2 = 1 + 1; guard if n == 0: return 1 if a caller can pass 0.

Common mistakes

  • Submitting plain unmemoized recursion: Finishes instantly on small samples (n = 1, 4, 6) and then times out on n = 45.
  • Initializing ways(2) = 1 instead of 2: Shifts the entire sequence down by one index (ways(4) becomes 3 instead of 5).
  • Clobbering one_step_back before updating two_steps_back: Writing one_step_back = one_step_back + two_steps_back followed by two_steps_back = one_step_back copies the new sum instead of the previous one_step_back. Compute current_ways first 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 to n = 45, IEEE-754 64-bit float precision drifts and produces wrong integers starting at n = 70.
  • Sharing a mutable default cache def climb_stairs(n, memo={}): Prefer creating memo inside 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 dictionary memo (or @functools.lru_cache). It runs in O(n) time and O(n) space and is easy to adapt when state transitions jump unevenly.
  • Matrix exponentiation: Raising the 2 x 2 transition matrix [[1, 1], [1, 0]] to power n via exponentiation by squaring (repeatedly squaring the matrix to halve the exponent at each step) computes ways(n) in O(log n) matrix multiplications.
  • Combinatorial binomial sum: Any sequence containing k strides of size 2 uses n - 2k strides of size 1, totaling n - k strides. Choosing which k positions are 2-strides gives the binomial coefficient C(n - k, k) (the number of ways to pick k slots from n - k), and summing C(n - k, k) over k = 0 .. n // 2 equals ways(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) to O(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 (RecursionError near n = 1000), removes function-call overhead, and compresses memory from O(n) down to O(1).
  • How would you generalize the solution if allowed move sizes came from an arbitrary positive integer set S? Group sequences reaching stair i by their final jump s in S: ways(i) = sum(ways(i - s) for s in S if s <= i), seeded with ways(0) = 1. Computing ways[0..n] bottom-up runs in O(n * len(S)) time and O(n) space (or O(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 iterate 10^18 times, 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 power n with exponentiation by squaring and taking every intermediate product % (10^9 + 7) finishes in O(log n) (~60) 2 x 2 matrix multiplications and O(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 blocked for O(1) membership checks, initialize ways(0) = 1 and ways(1) = 0 if 1 in blocked else 1, and during the bottom-up sweep set current_ways = 0 whenever step in blocked (otherwise one_step_back + two_steps_back). Zero sequences can pass through a blocked stair, while runtime stays O(n) and sliding-window space stays O(1).

Follow-up questions

Similar questions

More Paradromics interview questions

All 3 Paradromics questions →