AceYourInterviews
Checking sign-in…

142. Jump Game II — Minimum Jumps

IntermediateContiguous BFS layers compressed into two reachable frontiers

Starting at index zero, choose forward jumps within each position's permitted maximum. Among all routes that reach the final position, return the one requiring the fewest jumps.

Unlike the feasibility version, this problem asks for an optimal count. The input may be unreachable, and this course returns -1 in that case.

Example 1

Input

nums=[2,3,1,1,4]

Output

2

Explanation: The route 0→1→4 uses two jumps; the first jump cannot reach index four.

Example 2

Input

nums=[3,2,1,0,4]

Output

-1

Explanation: Every possible route remains inside indices zero through three.

Example 3

Input

nums=[0]

Output

0

Explanation: The starting index is already the destination.

Constraints

  • 0 <= nums.length <= 105
  • 0 <= nums[i] <= 231 - 1
Hints
Hint 1

Which indices can be reached with at most k jumps?

Hint 2

Can their union be summarized by a contiguous frontier?

Hint 3

Scan a complete frontier, accumulate the next reach, then count exactly one additional jump.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

A whole first layer chooses the stronger interior source

[2,3,0,0,0]
2