Stepping Stones Across the Creek

Easy · Greedy & Intervals · about 10 min

Stones cross a creek in a row. stones[i] is the longest jump you can make from stone i: from there you may jump forward 1, 2, ... up to stones[i] stones (a 0 means you cannot jump from that stone). You start on stone 0.

Return True if you can land on the last stone, otherwise False.

  • 1 ≤ len(stones) ≤ 10^5 and 0 ≤ stones[i] ≤ 10^5.

can_cross([2, 0, 3, 0, 0, 1]) → True (0 → 2 → 5)

can_cross([1, 2, 0, 0, 4]) → False

Hints

  • Instead of picking jumps, track the farthest stone you could reach so far.
  • Walk the stones in order. If a stone is past that farthest point, you are stuck.
  • Otherwise stretch the farthest point using this stone. You win if the farthest point reaches the last index.

Learn the pattern first: the Greedy & Intervals lesson.

More Greedy & Intervals problems