InterviewPrepKit

Home / Coding / 1-D Dynamic Programming

Climbing Stairs

easy Original β†—
Solving tips
  • Split on the last move: you reached step n from n-1 (a 1-step) or n-2 (a 2-step), giving f(n) = f(n-1) + f(n-2) - it's Fibonacci.
  • Use base cases f(0)=f(1)=1 (or f(1)=1, f(2)=2); a common slip is seeding f(2)=3.
  • Compute bottom-up with two rolling variables for O(n) time, O(1) space; naive recursion is O(2^n) and crawls near n=45.
  • Double-check n=1: with both variables seeded to 1 the loop is skipped and the correct 1 is returned.

Problem

A staircase has n steps. Starting from the ground, each move you may climb either 1 step or 2 steps. Count the number of distinct sequences of moves that land you exactly on the top step.

Two ways are different if at any point the size of the step taken differs.

Examples

  • n = 2 β†’ 2 β€” either 1 + 1 or 2.
  • n = 3 β†’ 3 β€” 1+1+1, 1+2, or 2+1.
  • n = 5 β†’ 8 β€” the count follows the Fibonacci sequence.

Constraints

  • 1 <= n <= 45

The tiny upper bound (45) means even an O(n) scan is instant; the point of the problem is to recognize the recurrence rather than to survive a large n. (The naive branching recursion, however, is O(2^n) and already crawls near n = 45.)

Think about it first

Hint 1 Focus on the *last* move that put you on step `n`. It was either a single step from `n-1` or a double step from `n-2`. Every full path ends with exactly one of those two moves.
Hint 2 So the number of ways to reach step `n` is the number of ways to reach `n-1` plus the number of ways to reach `n-2` β€” the two groups of paths are disjoint and together cover everything. What classic sequence is `f(n) = f(n-1) + f(n-2)`?
Hint 3 It's Fibonacci with base cases `f(1) = 1`, `f(2) = 2`. Compute it bottom-up keeping only the last two values, so no array and no recursion stack are needed β€” `O(n)` time, `O(1)` space.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.