πŸš€ Phases 1–5 are live β€” Days 1–17 cover the foundations and the algorithmic patterns. See the roadmap β†’

Climbing Stairs easy

Description

You’re climbing a staircase. It takes n steps to reach the top. Each time you can climb either 1 or 2 steps. In how many distinct ways can you climb to the top?

Examples

> Case 1:
    n = 2
    Output: 2
    Explanation: 1+1, or 2.
 
> Case 2:
    n = 5
    Output: 8
    Explanation: 1+1+1+1+1, 1+1+1+2, 1+1+2+1, 1+2+1+1,
                 2+1+1+1, 1+2+2, 2+1+2, 2+2+1

Constraints

  • 1 <= n <= 45

State design

  1. What am I computing? Number of distinct ways to reach step i.
  2. Dimensions? One β€” just i.
  3. Base cases? dp[0] = 1 (one way to be at the start β€” don’t move), dp[1] = 1.
  4. Transition? dp[i] = dp[i - 1] + dp[i - 2]. To reach step i, the last move was a 1-step (from i - 1) or a 2-step (from i - 2).
  5. Order? Increasing i.

The recurrence is Fibonacci with shifted base cases. Same shape, same O(n) solution.

Code

The β€œI can climb k steps at a time” generalization turns this into dp[i] = sum(dp[i - 1], dp[i - 2], ..., dp[i - k]). Same shape, longer window. Interviewers love asking this follow-up.

Analysis

  • Time: O(n) β€” one pass.
  • Space: O(1) β€” two rolling variables.