Climbing Stairs

EasyDynamic Programming · 1-D DP🧩 1-D Dynamic ProgrammingLeetCode #70 ↗Updated

Problem

A staircase has n steps. On every move you climb either 1 or 2 steps. Count how many distinct sequences of moves take you from the ground exactly to the top.
Inputn = 2Output2 (1+1, 2)
Inputn = 3Output3 (1+1+1, 1+2, 2+1)

1 ≤ n ≤ 45  ·  answer fits in a 32-bit int

Try it yourself

Java
class Solution {
    public int climbStairs(int n) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Look at the last move: you reached step n either from n-1 or from n-2. So ways(n) = ways(n-1) + ways(n-2) — it is Fibonacci, and only the last two values are ever needed.
Pattern1-D Dynamic Programming

Instinct The best answer at position i depends only on a few earlier positions (i-1, i-2, ...) - write dp[i] from its predecessors, then roll it into variables.

Memory hack Look back, pick best, roll forward - every step only remembers the last couple of stairs it stood on.

Open the 1-D Dynamic Programming guide →

Approaches

Brute ForcePlain Recursion

Time O(2n)Space O(n)

Directly code the recurrence: from step i try a 1-step and a 2-step move and add the counts. The call tree branches twice per level and recomputes the same steps over and over (ways(n-2) is solved twice, etc.).

Java
public int climbStairs(int n) {
    return climb(0, n);
}
private int climb(int i, int n) {
    if (i > n) return 0;   // overshot the top
    if (i == n) return 1;  // landed exactly on top
    return climb(i + 1, n) + climb(i + 2, n);
}

Correct and tiny, but exponential — n = 45 needs ~109 calls.

At a glance

LevelApproachTimeSpace
Brute ForcePlain RecursionO(2n)O(n)
BetterTop-Down MemoizationO(n)O(n)
OptimalBottom-Up, Two VariablesO(n)O(1)
Common pitfalls
  • Missing the overshoot base case (i > n) — infinite or wrong recursion.
  • Using 0 as “not computed” only works because every answer is ≥ 1.
  • Returning prev2 instead of prev1 — off by one step.
Interview tips
  • Derive the recurrence from the last move; then say “this is Fibonacci”.
  • Walk the ladder: recursion → memo → table → two variables.
  • Mention O(log n) matrix exponentiation as a follow-up if asked.
Pattern
1-D DP (Fibonacci-style) → count ways where each state depends on a fixed number of previous states.
My notes saved in this browser