Problem 555604 · medium · Phase 05 Advanced Algorithms & Graphs

Fewest Hops

dynamic programming · 1-D dp · min steps · range expansion

Stepping stones cross a river. Standing on stone i you may hop forward to any stone from i + 1 up to i + reach[i] (a 0 means the stone is slippery and you cannot leave it). Starting on stone 0, return the minimum number of hops needed to stand on the last stone, or -1 if it cannot be reached. Being on the only stone needs 0 hops.

Examples

Input:  reach = [2, 3, 1, 1, 4]
Output: 2
Explanation: stone 0 -> stone 1 -> stone 4.

Input:  reach = [3, 2, 1, 0, 4]
Output: -1
Explanation: every route is forced onto stone 3, which cannot be left.

Constraints

  • 1 <= len(reach) <= 10**5
  • 0 <= reach[i] <= 10**5
  • Target complexity: O(n) time; an O(n^2) table is too slow for the largest tests.

Goals

  • Track the farthest index reachable with a given number of hops
  • Detect an impossible crossing and return -1
Starting Python…