Stepping Stones Across the Pond

Easydynamic programmingAlso known as Climbing Stairs

A pond has a straight line of n stepping stones, and the last one touches the far bank. A child crosses from the near bank 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 one after.

She wants to cross a different way every day, so she needs to know how many different crossings exist.

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 differ if their sequences of moves differ. 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

With no hops there is only one crossing, five steps. With one hop there are 4 moves in total and the hop can be any of them, which gives 4 crossings. With two hops there are 3 moves and the single step can be first, second or third, which gives 3 crossings. Three hops would cover 6 positions, which is past the last stone. The total is 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 recursively: count(i) = count(i - 1) + count(i - 2), stopping at the bank. This is correct and short, but it is slow.

The running time is exponential, because count(70) calls count(69) and count(68), and count(69) calls count(68) again. The number of calls grows like the answer itself, hundreds of trillions for n = 70.

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