InterviewPrepKit

Home / Coding / Algorithm & Data Structure / 1-D Dynamic Programming

Climbing Stairs

easy Original ↗ 00:00

Problem

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

Two sequences differ if the step size taken differs at any point.

Examples

  • n = 22 — either 1 + 1 or 2.
  • n = 331+1+1, 1+2, or 2+1.
  • n = 58 — the count follows the Fibonacci sequence.

Constraints

  • 1 <= n <= 45

The upper bound is small, so even an O(n) scan runs instantly; the problem tests whether you recognize the recurrence, not whether your code scales. Naive branching recursion is O(2^n) and already becomes slow near n = 45.

Think about it first

Hint 1 Focus on the last move onto step `n`. It was either a single step from `n-1` or a double step from `n-2`. Every complete path ends with exactly one of these 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug