Index

Free, with Google

Keep going, free.

A free account opens lessons 2 and 3 of every track, 33 more lessons, and keeps your progress and review cards on every device.

Start free with Google

A chalk plan

Open everything on chalk.

Every lesson, board, video, lab and paper, and the full review decks. Yearly is $39/year.

See plansStart free instead

Climbing Stairs

EasyLeetCode 70 ↗

The problem, in one line. A staircase has n steps and you climb one or two at a time, so count the different ways to reach the top. LeetCode 70.

The tell. “How many ways” where the last move is one of a few fixed choices. Whenever the answer for a size is built from the answers for smaller sizes, store the small answers and add them.

The wrong first idea

Recurse straight from the top: ways to reach n is ways to reach n-1 plus ways to reach n-2.

def ways(n):
    return 1 if n <= 1 else ways(n - 1) + ways(n - 2)

It is correct, but it recomputes the same smaller stairs again and again. For n = 45 the answer is 1,836,311,903, and the recursion adds ones one at a time, so it makes nearly 3.7 billion calls.

The invariant

The full walkthrough is in Clinic #02: Climbing Stairs. In short: you stood on step n after a hop of 1 or a hop of 2, and those two cases never overlap. So the count for n is the count for n-1 plus the count for n-2.

flowchart LR
  A["step 3: 3 ways"] -->|"hop 2"| C["step 5: 3 + 5 = 8"]
  B["step 4: 5 ways"] -->|"hop 1"| C

The sentence that stays true every step: the two numbers I hold are the ways to stand on the last two steps. That is why two variables replace a whole table.

The solution

def climb_stairs(n):
    a, b = 1, 1                    # ways to stand on step 0 and step 1
    for _ in range(n - 1):
        a, b = b, a + b            # the last hop was 1 or 2, so add the two before
    return b

print(climb_stairs(2))
print(climb_stairs(5))
print(climb_stairs(45))
2
8
1836311903
func climbStairs(n int) int {
	a, b := 1, 1 // ways to stand on step 0 and step 1
	for i := 0; i < n-1; i++ {
		a, b = b, a+b // the last hop was 1 or 2, so add the two before
	}
	return b
}

Same three calls print 2, 8, 1836311903.

Complexity

  • Time O(n): one addition per step.
  • Space O(1): only the last two counts are ever needed.

Traps

  • Starting both counts at 0. The loop then adds zeros forever and returns 0 for every n.
  • Looping one time too many or too few. For n = 1 the loop must run zero times, and the answer is 1.
  • Using a 32-bit integer in a language without big numbers for n above 45. The answer for 46 is 2,971,215,073 and overflows.

Next in the ladder

Min Cost Climbing Stairs keeps the same two-step hop, but each step now has a price and you want the cheapest climb, so the addition becomes a minimum.