File: climbing-stairs/solution.py

Date: 2026-06-06

Time: 15:46

climbing-stairs/solution.py

Purpose

This file solves LeetCode 70 — Climbing Stairs: given n stairs where you can climb 1 or 2 steps at a time, return the number of distinct ways to reach the top. It's a classic dynamic programming problem whose answer is the (n+1)th Fibonacci number.

Key Components

Solution.climbStairs(self, n: int) -> int — the single method, following LeetCode's expected class/method signature.

Patterns

Space-optimized Fibonacci recurrence. The number of ways to reach stair k is ways(k-1) + ways(k-2) — you can arrive from one step below or two steps below. Since each state depends only on the previous two, the solution keeps just two rolling variables (a, b) instead of an array. This is the standard idiom for 1D DP problems with a fixed lookback window.

The tuple swap a, b = b, a + b is a Python idiom that updates both values simultaneously without a temporary variable — identical to computing the next Fibonacci number.

Dependencies

Imports: None. The solution is self-contained.

Imported by: The climbing-stairs/test_solution.py file directly, plus the "Imported By" list in the prompt shows hundreds of other test files. That's an artifact of the repo's test infrastructure — those test files likely share a common test harness or import pattern, not a direct dependency on this solution's logic.

Flow

1. If n is 1 or 2, return n immediately.

2. Initialize a = 1 (ways to reach stair 1), b = 2 (ways to reach stair 2).

3. Loop from 3 to n inclusive. Each iteration advances the window: a becomes the old b, b becomes the old a + b.

4. After the loop, b holds the answer for stair n.

For n = 5:


Start:       a=1, b=2
i=3:         a=2, b=3
i=4:         a=3, b=5
i=5:         a=5, b=8
Return 8

Invariants

Error Handling

None. The function assumes valid input per the problem constraints. Passing n <= 0 would return n (0 or negative), which is technically wrong but outside the contract. No exceptions are raised.

Topics to Explore

Beliefs