SDE & MLE Prep

70. Climbing Stairs

Problem

You climb a staircase of n steps, taking 1 or 2 steps at a time. In how many distinct ways can you reach the top?

Example: n = 2 → 2; n = 5 → 8

Constraints: n ≤ 45.

To reach step i you came from i−1 or i−2: ways(i) = ways(i−1) + ways(i−2). Keep two variables.

Complexity: O(n) time, O(1) space.

class Solution:
    def climbStairs(self, n: int) -> int:
        a, b = 1, 1          # ways(0), ways(1)
        for _ in range(n - 1):
            a, b = b, a + b
        return b