Python coding

Fewest jumps to the last tile

You stand on the first tile of a row. jumps[i] is the longest jump forward you may take from tile i; any shorter jump is allowed too. Return the fewest jumps that land you on the last tile, or -1 if no sequence of jumps gets there.

jumps has at least one tile and its values are non-negative. Aim for one pass and O(1) extra space.

Besides the tests, one large input (6,000 tiles) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • fewest_jumps([2,3,0,1,4]) → 2
  • fewest_jumps([1,1,1,1]) → 3
  • fewest_jumps([2,1,0,3]) → -1
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Think of a BFS by levels: the tiles reachable with 0 jumps, then with 1, then with 2. Each level is a contiguous range of tiles, so two indexes describe it.

Hint 2

Scan left to right keeping end, the last tile of the current level, and reach, the farthest tile any tile so far can jump to. When i reaches end, count a jump and set end = reach.

Hint 3

Stop the scan before the last tile, or you count a jump out of it. If you must jump but reach is not past end, no new tile is reachable: return -1.

Solution and why it works
pythonO(n) · O(1)
def fewest_jumps(jumps: list[int]) -> int:
    hops = end = reach = 0               # tiles 0..end are reachable in `hops` jumps
    for i in range(len(jumps) - 1):      # never jump out of the last tile
        reach = max(reach, i + jumps[i])
        if i == end:                     # this level is used up: one more jump
            if reach <= end:             # and it reaches no new tile
                return -1
            hops, end = hops + 1, reach
    return hops

Tiles reachable in k jumps form one contiguous range, since shorter jumps are allowed. This is a BFS by levels where each level is a range: while scanning it, track the farthest tile reachable from inside it; that tile is where the next level ends. Each tile is read once: O(n) time and O(1) space, where a DP over every jump length is O(n²). Traps: always jumping as far as possible (3 jumps on [2, 3, 1, 1, 4] instead of 2), and missing the stuck case.