SDE & MLE Prep

45. Jump Game II

Problem

You start at index 0, and nums[i] is the maximum jump length from index i. Return the minimum number of jumps to reach the last index (always possible).

Example: [2,3,1,1,4] → 2 (0 → 1 → 4)

Constraints: n ≤ 10⁴.

BFS by "levels": the current jump covers [.., end]; while scanning it, track the farthest next reach. When you hit end, you must jump: jumps += 1, end = farthest.

nums 2 3 1 1 4
     [0]           jump 1 covers 1..2
       [1  2]      farthest = 4  -> jump 2 reaches the end

Complexity: O(n).

class Solution:
    def jump(self, nums: List[int]) -> int:
        jumps = end = far = 0
        for i in range(len(nums) - 1):
            far = max(far, i + nums[i])
            if i == end:
                jumps += 1
                end = far
        return jumps