InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Greedy

Jump Game II

medium Original ↗ 00:00

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]20→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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug