Stepping Stones Across the Pond

Easydynamic programmingAlso known as Climbing Stairs

A garden pond has a straight line of n stepping stones. The last stone touches the far bank. A child stands on the near bank and crosses one move at a time. Each move is either a step onto the next stone, or a hop that skips one stone and lands on the stone after it.

She wants to cross a different way every day. How many different crossings are there before she has to repeat one?

Your task

Write countCrossings(n). Return the number of different sequences of steps and hops that start on the near bank and end exactly on stone n.

The near bank is position 0 and the stones are positions 1 to n. A step moves 1 position, a hop moves 2. Two crossings are different if their sequences of moves are different. She may not hop past stone n.

countCrossings(n: int) → int

Examples

Example 1
Input
n = 3
Output
3
Why

The three crossings are step-step-step, step-hop and hop-step. Step-hop and hop-step land on different stones on the way, so they count as two different crossings.

Example 2
Input
n = 5
Output
8
Why

No hops: step-step-step-step-step, 1 way. One hop: 4 moves in total, and the hop can be any of the 4, so 4 ways. Two hops: 3 moves, and the single step can be first, second or third, so 3 ways. Three hops would be 6 positions, past the last stone. 1 + 4 + 3 = 8.

Constraints

  • 1 ≤ n ≤ 70
  • The answer fits in a normal integer (it is below 10¹⁵ for n = 70).
Start with brute force

Write the rule as a recursive function: count(i) = count(i - 1) + count(i - 2), stopping at the bank. It is short and correct.

It is also exponential. count(70) calls count(69) and count(68), and count(69) calls count(68) again, and so on. The number of calls grows like the answer itself: hundreds of trillions for n = 70. The same few subproblems get solved over and over.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code