InterviewPrepKit

Home / Coding / Greedy

Jump Game II

medium Original β†—
Solving tips
  • Think of this as BFS in disguise: each 'layer' is the contiguous range reachable in exactly k jumps, and the answer is the layer holding the last index.
  • Track cur_end (end of current layer) and farthest reach; increment jumps only when i reaches cur_end, then set cur_end = farthest.
  • Iterate only to n-2, never from the last index, or you'll count a phantom jump.
  • Target O(n) time and O(1) space; the jump count equals the number of layers, not the number of steps.

Problem

You are given an integer array nums. You start at index 0, and each nums[i] is the maximum jump length from index i (you may land on any index in i+1 .. i+nums[i]). It is guaranteed you can reach the last index. Return the minimum number of jumps needed to get from index 0 to the last index.

Examples

  • nums = [2,3,1,1,4] β†’ 2 β€” jump 0β†’1 (length 1), then 1β†’4 (length 3): two jumps.
  • nums = [2,3,0,1,4] β†’ 2 β€” 0β†’1, then 1β†’4, again two jumps.
  • nums = [0] β†’ 0 β€” already at the last index, no jump needed.

Constraints

  • 1 <= len(nums) <= 10^4
  • 0 <= nums[i] <= 1000
  • It is guaranteed you can reach nums[len(nums) - 1].

An O(n) solution is expected; the O(n^2) DP is too slow at the upper bound.

Think about it first

Hint 1 Think in "layers," like breadth-first search. Layer 0 is index 0. Layer 1 is every index reachable in one jump. Layer 2 is everything reachable from layer 1 in one more jump. The answer is the layer number containing the last index.
Hint 2 You do not need which specific index you jump to β€” only the farthest index the current layer can reach. Track the end of the current layer and the farthest reach discovered while scanning it.
Hint 3 Sweep i from 0 to n-2. Keep farthest = max(farthest, i + nums[i]). When i hits the current layer's end, you must jump: increment the count and set the new layer end to farthest.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.