medium Jump Game II
Problem Statement
You are given an array nums containing n integers, where nums[i] represents the maximum length of a forward jump you can make from index i. You are initially positioned at nums[0].
Return the minimum number of jumps needed to reach from the start to the end of the array.
Examples
Example 1:
- Input: nums =
[2, 3, 2, 2, 1] - Expected Output: 2
- Justification: Start at index 0 and jump to index 1 (jump size 1). Then, jump from index 1 to the end (jump size 3).
Example 2:
- Input: nums =
[1, 2, 3, 4, 5] - Expected Output: 3
- Justification: Start at index 0, jump to index 1 (jump size 1). Then, jump to index 3 (jump size 2). Finally, jump to the end (jump size 2).
Example 3:
- Input: nums =
[2, 3, 1, 2, 4, 1] - Expected Output: 3
- Justification: Start at index 0, jump to index 1 (jump size 1). Then, jump to index 4 (jump size 2). Finally, jump to the end (jump size 1).
Constraints:
- 1 <= nums.length <= 104
- 0 <= nums[i] <= 1000
- It's guaranteed that you can reach nums[n - 1].
Try it yourself
Try solving this question here:
After you try — Pattern Transfer
Pattern: GREEDY FARTHEST-REACH as BFS LAYERS (min jumps).
vs Jump I: Jump I asks reachability (boolean). Jump II asks shortest path length in the same implicit unweighted graph (each index → up to nums[i] steps ahead).
When NOT: end not guaranteed reachable → run Jump I / detect stuck first; weighted jumps → Dijkstra/DP.
Edges
- Single element
[0]or[1] → 0jumps (already at end). - All ones of length n → n−1 jumps.
🎯 STRICT STANDOUT — Jump Game II
1. Why / judgment
Min jumps is shortest path in an unweighted implicit graph (edge i→i+1…i+nums[i]). BFS layers = greedy farthest-reach: while exploring the current jump’s range, track the farthest next range; when the range ends, +1 jump. Same idea as Jump I reachability, but you count layers.
2. Worked layer trace + complexity (K11)
nums = [2,3,1,1,4] (classic; similar to page examples)
jumps=0, curEnd=0, farthest=0
i=0: farthest=max(0,0+2)=2; i==curEnd → jumps=1, curEnd=2
i=1: farthest=max(2,1+3)=4
i=2: farthest=max(4,2+1)=4; i==curEnd → jumps=2, curEnd=4
i reaches n-1 with jumps=2 ✓
Each index visited once → Θ(n) time, Θ(1) extra space.
DP jumps[i]=min over j reachable: Θ(n²) worst — worse class, unnecessary when end guaranteed reachable.
BFS queue explicit: Θ(n) time, Θ(n) space — same asymptotic time, more memory.
3. Pattern — GREEDY FARTHEST = BFS LAYERS (K12)
Name: Jump II min-jumps greedy.
Recognition: min jumps / levels in unit-weight jump graph; “how many moves to end”.
When-NOT: end not guaranteed → detect stuck (Jump I / return −1); weighted jump costs → Dijkstra/0-1 BFS; need path reconstruction → parent pointers, not only count.
4. Edge hand-run (K13)
[0] or [1] single cell already at end → 0 jumps
[1,1,1,1] → n−1 = 3 jumps
[2,3,2,2,1] page ex → 2 jumps (0→1→4)
5. Interviewer follow-ups
Q1. Jump I vs Jump II?
A: I = boolean reachability; II = shortest path length in same graph.
Q2. Why O(n) not O(n²)?
A: Each index processed once; farthest scan covers edges implicitly without nested restarts.
Q3. What if zeros can trap you?
A: Constraints here guarantee reachability; otherwise fail when i==curEnd and farthest==i before end.
✅ Solution Jump Game II
Problem Statement
You are given an array nums containing n integers, where nums[i] represents the maximum length of a forward jump you can make from index i. You are initially positioned at nums[0].
Return the minimum number of jumps needed to reach from the start to the end of the array.
Examples
Example 1:
- Input: nums =
[2, 3, 2, 2, 1] - Expected Output: 2
- Justification: Start at index 0 and jump to index 1 (jump size 1). Then, jump from index 1 to the end (jump size 3).
Example 2:
- Input: nums =
[1, 2, 3, 4, 5] - Expected Output: 3
- Justification: Start at index 0, jump to index 1 (jump size 1). Then, jump to index 3 (jump size 2). Finally, jump to the end (jump size 2).
Example 3:
- Input: nums =
[2, 3, 1, 2, 4, 1] - Expected Output: 3
- Justification: Start at index 0, jump to index 1 (jump size 1). Then, jump to index 4 (jump size 2). Finally, jump to the end (jump size 1).
Constraints:
- 1 <= nums.length <= 104
- 0 <= nums[i] <= 1000
- It's guaranteed that you can reach nums[n - 1].
Solution
To solve this problem, we need to keep track of the farthest point we can reach with each jump and count how many jumps we need. The strategy is to iterate through the array while updating the farthest point we can reach. Whenever we reach the end of the current jump range, we increment our jump count and update the current jump range to the farthest point we can reach. This method ensures that we use the fewest jumps possible to get to the end.
This approach works effectively because it uses a greedy algorithm to always make the optimal choice at each step. By focusing on the farthest reachable point, we minimize the number of jumps needed.
Step-by-Step Algorithm
-
Initialize Variables:
- Create a variable
jumpsand set it to 0. This will count the number of jumps needed. - Create a variable
currentEndand set it to 0. This will mark the end of the range for the current jump. - Create a variable
farthestand set it to 0. This will track the farthest point that can be reached.
- Create a variable
-
Loop Through the Array:
- Iterate through the array from the first element to the second-to-last element (from index 0 to n-2):
- Update
farthestto be the maximum offarthestand the current index plus the jump length at that index (farthest = max(farthest, i + nums[i])). - If the current index is equal to
currentEnd:- Increment the
jumpscount (jumps++). - Update
currentEndto befarthest(currentEnd = farthest).
- Increment the
- Update
- Iterate through the array from the first element to the second-to-last element (from index 0 to n-2):
-
Return Result:
- After the loop ends, return the value of
jumpsas the result.
- After the loop ends, return the value of
Algorithm Walkthrough
Using the input nums = [2, 3, 1, 2, 4, 1].
Initialization:
jumps = 0currentEnd = 0farthest = 0
Iteration 1:
- Index
i = 0farthest = max(0, 0 + 2) = 2- Since
i == currentEnd(0 == 0):jumps++(jumps = 1)currentEnd = farthest(currentEnd = 2)
Iteration 2:
- Index
i = 1farthest = max(2, 1 + 3) = 4i != currentEnd(1 != 2), so do nothing
Iteration 3:
- Index
i = 2farthest = max(4, 2 + 1) = 4- Since
i == currentEnd(2 == 2):jumps++(jumps = 2)currentEnd = farthest(currentEnd = 4)
Iteration 4:
- Index
i = 3farthest = max(4, 3 + 2) = 5i != currentEnd(3 != 4), so do nothing
Iteration 5:
- Index
i = 4farthest = max(5, 4 + 4) = 8- Since
i == currentEnd(4 == 4):jumps++(jumps = 3)currentEnd = farthest(currentEnd = 8)
Return Result:
- Return
jumpswhich is 3.
Code
public class Solution {
public int jump(int[] nums) {
int jumps = 0; // To count the number of jumps
int currentEnd = 0; // To mark the end of the range for the current jump
int farthest = 0; // To mark the farthest point that can be reached
// Loop through the array
for (int i = 0; i < nums.length - 1; i++) {
farthest = Math.max(farthest, i + nums[i]); // Update the farthest point
if (i == currentEnd) { // If reached the end of the current jump range
jumps++; // Increment jump count
currentEnd = farthest; // Update the end of the range to the farthest point
}
}
return jumps; // Return the number of jumps
}
public static void main(String[] args) {
Solution solution = new Solution();
// Test examples
int[] example1 = { 2, 3, 2, 2, 1 };
int[] example2 = { 1, 2, 3, 4, 5 };
int[] example3 = { 2, 3, 1, 2, 4, 1 };
// Print the results
System.out.println(solution.jump(example1)); // Expected Output: 2
System.out.println(solution.jump(example2)); // Expected Output: 3
System.out.println(solution.jump(example3)); // Expected Output: 3
}
}
Complexity Analysis
- Time Complexity: The algorithm runs in
time, where nis the length of the array. This is because we iterate through the array once, and each operation inside the loop (like updating the farthest point) takes constant time. - Space Complexity: The algorithm uses
additional space since we are only using a few extra variables (jumps, currentEnd, and farthest) regardless of the input size.
Pattern Transfer — GREEDY FARTHEST-REACH as BFS LAYERS (Jump II)
Pattern: treat indices as an unweighted graph; each jump is a BFS layer. currentEnd is the layer boundary; farthest is the farthest reach discoverable in this layer; when i hits currentEnd, start a new jump.
Template:
jumps = 0
end = 0
far = 0
for i in 0 .. n-2: # last index needs no outbound jump
far = max(far, i + nums[i])
if i == end:
jumps += 1
end = far
return jumps
Assumption: the end is reachable (LeetCode 45 style). If not guaranteed, run Jump I first or detect when end cannot advance.
When NOT: only reachability → Jump I (simpler loop). Weighted jumps → Dijkstra/DP. Naive DP min-jumps O(n²).
Complexity: one pass over n−1 indices → Θ(n) time, O(1) space.
Verified walkthrough: [2,3,1,2,4,1] layer ends 0→2→4→≥5, jumps=3 (no 2-jump path to last index).
Edge hand-runs
[1]: loop range 0..−1 empty → jumps 0. Explains loop boundn-2: last index never needs an outbound jump.[1,1,1] → 2.
Drill: Why is this BFS shortest path without a queue? (Each layer’s frontier is the contiguous index range (prevEnd, end].)
Recognize it: A locally-optimal choice is provably globally optimal → take the best step now (often after sorting).
▶ Visualize this problem (step it, predict each fork)
🤖 Don't fully get this? Learn it with Claude
Stuck on Jump Game II? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Jump Game II** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Jump Game II** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Jump Game II**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Jump Game II**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.