← All problems
#70EasyπŸ”’ Pattern ???

Climbing Stairs

A staircase has n steps. Each move climbs either 1 or 2 steps. How many distinct ways are there to reach the top?

Try it on LeetCode
πŸ€” GUESS THE PATTERN+5 XP

Before you peek at the solution: which pattern do you think this one uses?

Hints0/3

Optional. Open them one at a time if you're stuck.

🎬 Walkthrough video

Video coming soon

The video is still being edited. Meanwhile, read the explanation and the code.

πŸ“ Explanation

Intuition

To land on step n, your last move came either from n - 1 (a 1-step) or from n - 2 (a 2-step). So:

ways(n) = ways(n - 1) + ways(n - 2)

Plain recursion recomputes the same subproblems over and over, which takes O(2ⁿ). Dynamic programming stores the results so you never compute twice.

Steps

  1. Base cases: ways(1) = 1, ways(2) = 2.
  2. Build bottom-up, keeping only the last two values a and b.
  3. Repeat a, b = b, a + b for n - 1 rounds.

Fun fact

The answers are the Fibonacci sequence shifted by one.

⏱️ Complexity

TimeO(n)
SpaceO(1)

πŸ’» Solution code

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

Got it and submitted?

Mark it solved to earn XP and keep your streak alive.