sagelearnai

Jump Game II

Difficulty: Medium · Pattern: Greedy · LeetCode #45

Same jumping rules as Jump Game, but now the last index is guaranteed reachable. Return the minimum number of jumps to reach it.

Examples

text
nums = [2, 3, 1, 1, 4]  →  2    (0 → 1 → 4)
nums = [2, 3, 0, 1, 4]  →  2
nums = [1]              →  0

Hints

  1. Think of BFS: all indices reachable with k jumps form a contiguous range.
  2. Track the end of the current range and the farthest index reachable from inside it.
  3. When you pass the end of the current range, you must take another jump.

Approach

Treat indices reachable in k jumps as BFS level k, which is always a contiguous window. Scan i from 0 to n − 2, tracking far = max(far, i + nums[i]). When i reaches curEnd (the end of the current level), take a jump: jumps += 1, curEnd = far. Stopping at n − 2 avoids counting an extra jump at the last index.

Complexity

Time: O(n). Space: O(1).

Python solution
def jump(nums):
    jumps = cur_end = far = 0
    for i in range(len(nums) - 1):
        far = max(far, i + nums[i])
        if i == cur_end:
            jumps += 1
            cur_end = far
    return jumps
JavaScript solution
function jump(nums) {
  let jumps = 0, curEnd = 0, far = 0;
  for (let i = 0; i < nums.length - 1; i++) {
    far = Math.max(far, i + nums[i]);
    if (i === curEnd) { jumps++; curEnd = far; }
  }
  return jumps;
}