Algorithm Day80 - Jump Game II

🧩 Problem Description

You are given a 0-indexed array of integers nums of length n. You are initially positioned at the first index.
Each element nums[i] represents the maximum length of a forward jump from index i.

Return the minimum number of jumps to reach the last index. The test cases are generated such that you can always reach the last index.


💬 Examples

Example 1

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

Example 2

1
2
Input: nums = [2,3,0,1,4]
Output: 2

💡 Intuition

This problem can be solved using a greedy approach.

  • We want to minimize the number of jumps.
  • Track two variables while scanning:
    • currentEnd: the farthest point reachable with the current number of jumps.
    • farthest: the farthest point reachable by the next jump.
  • Each time we reach currentEnd, we must make another jump, and update currentEnd = farthest.

This guarantees minimum jumps since we always extend as far as possible at each step.


🔢 Java Code (Greedy)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int jump(int[] nums) {
int jumps = 0;
int farthest = 0;
int currentEnd = 0;
for (int i = 0; i < nums.length - 1; i++) {
farthest = Math.max(farthest, i + nums[i]);
if (i == currentEnd) {
jumps++;
currentEnd = farthest;
}
}
return jumps;
}
}

⏱ Complexity Analysis

  • Time: O(n) — linear scan.
  • Space: O(1).

✍️ Summary

  • Use a greedy strategy to expand the farthest reach at each step.
  • Each time you exhaust the current range, increment jumps and move to the next range.
  • Efficient O(n) solution.

Related problems

  • lc-55 — Jump Game
  • lc-1306 — Jump Game III
  • lc-1345 — Jump Game IV