Jump Game II

Medium
greedy

You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0].

Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where:

  • 0 <= j <= nums[i] and
  • i + j < n

Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1].

Greedy Insight: Use a "level-based" approach like BFS. At each "level" (jump), determine the farthest you can reach. When you've exhausted the current level's range, increment jumps and extend to the new maximum.

Why Greedy Works: By always jumping to the position that maximizes our next reach, we minimize total jumps. We greedily extend our range at each level.

Example 1

Input: nums = [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2

Input: nums = [2,3,0,1,4]
Output: 2
Explanation: Jump from index 0 to 1 (value 3), then jump 3 steps to reach the end.

Constraints

  • 1 <= nums.length <= 10^4
  • 0 <= nums[i] <= 1000
  • It's guaranteed that you can reach nums[n - 1]
Show Hints (4)
Hint 1: Think of this as BFS where each "level" is a jump.
Hint 2: Track the current jump's boundary and the farthest you can reach from the current level.
Hint 3: When you reach the current boundary, you must make a jump to continue.
Hint 4: Update the boundary to the farthest reach when you jump.
Loading editor...

Test Results

Click "Run" to execute your code against test cases

AI Tutor

Socratic guidance - I'll ask questions, not give answers

AI Tutor
Hello! I'm your AI tutor, here to guide you through this problem using the Socratic method. I won't give you direct answers, but I'll ask questions and provide hints to help you discover the solution yourself. What's your first instinct when you look at this problem? What approach comes to mind?