Climbing Stairs
The problem
Section titled “The problem”You are at the bottom of a staircase with n steps. Each move climbs 1 or 2 steps.
Return how many different sequences of moves reach the top.
n = 3 -> 3 (1+1+1, 1+2, 2+1)Key insight
Section titled “Key insight”Brute force tries every sequence of moves, which is O(2^n). The waste is that it recomputes the same sub-question again and again: “how many ways to reach step k?”
To land on step n, your last move came from step n-1 (a 1-step) or from step n-2
(a 2-step). Those two groups never overlap, so the counts add:
ways[i] = ways[i-1] + ways[i-2], with ways[0] = 1 and ways[1] = 1. This is the
Fibonacci sequence. Each value only needs the previous two, so keep two variables
instead of an array.
Show solutionHide solution
def climb_stairs(n: int) -> int: prev, cur = 1, 1 # ways to reach step 0 and step 1 for _ in range(2, n + 1): prev, cur = cur, prev + cur return curexport function climbStairs(n: number): number { let prev = 1, cur = 1; // ways to reach step 0 and step 1 for (let i = 2; i <= n; i++) { [prev, cur] = [cur, prev + cur]; } return cur;}class Solution { public int climbStairs(int n) { int prev = 1, cur = 1; // ways to reach step 0 and step 1 for (int i = 2; i <= n; i++) { int next = prev + cur; prev = cur; cur = next; } return cur; }}Complexity
Section titled “Complexity”- Time: O(n) — one loop from step 2 to step
n, constant work per step. - Space: O(1) — only two rolling variables, no table.
Watch out for
Section titled “Watch out for”- Base cases.
ways[0] = 1(do nothing) andways[1] = 1. Starting both at 0, or returning the wrong value forn = 1, is the classic bug. - Don’t recurse without memoization. Plain recursion is O(2^n) and times out.
- No overflow here. With
n <= 45the answer fits in a 32-bit int, so nolongneeded.
Variations
Section titled “Variations”Min Cost Climbing Stairs (LeetCode 746)
Section titled “Min Cost Climbing Stairs (LeetCode 746)”Each step has a cost and you may start on step 0 or 1; find the cheapest way past the
last step. The trick: same two-back recurrence, but take a minimum instead of a sum:
cost_to_reach[i] = min(cost_to_reach[i-1] + cost[i-1], cost_to_reach[i-2] + cost[i-2]).
N-th Tribonacci Number (LeetCode 1137)
Section titled “N-th Tribonacci Number (LeetCode 1137)”Each term is the sum of the previous three. The trick: the same rolling-variable idea with three variables instead of two. Shift them forward each iteration.
Fibonacci Number (LeetCode 509)
Section titled “Fibonacci Number (LeetCode 509)”Return the n-th Fibonacci number. The trick: it is this problem with different base
cases (F(0) = 0, F(1) = 1). Use two rolling variables.