Skip to content

Climbing Stairs

EasyLeetCode #70Time O(n)Space O(1)

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)

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 cur
  • Time: O(n) — one loop from step 2 to step n, constant work per step.
  • Space: O(1) — only two rolling variables, no table.
  • Base cases. ways[0] = 1 (do nothing) and ways[1] = 1. Starting both at 0, or returning the wrong value for n = 1, is the classic bug.
  • Don’t recurse without memoization. Plain recursion is O(2^n) and times out.
  • No overflow here. With n <= 45 the answer fits in a 32-bit int, so no long needed.

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]).

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.

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.