Jump Game II: The Two-Variable Greedy That Beats DP by 30x, With Proofs and Interview Traps
LeetCode 45 Jump Game II: The Greedy Problem Interviewers at Big Tech Love to Ask About, and I've Stripped the Bones Clean for You
Last week I interviewed three candidates, and all of them stumbled on the same problem — LeetCode 45 "Jump Game II". This problem appears with absurdly high frequency at ByteDance, Tencent, and Kuaishou (medium difficulty, pass rate about 46%). It's the classic "easy to understand at a glance, wrong on the second write, and only shows your true skill after three levels of follow-up". The code is only ten lines, but people who get the i < n - 1 boundary wrong could circle the office. This article thoroughly explains the complete derivation from brute force → DP → BFS → greedy, the correctness proof, common pitfalls, and prepared responses for follow-up questions. It's for those who are practicing problems and preparing for interviews, or who want to truly understand greedy algorithms.
1. Chew the problem up: don't rush to write code
One-sentence version: You are given a non-negative integer array nums, starting at index 0. nums[i] is the maximum number of steps you can jump forward from index i (you can jump fewer, not necessarily the full amount). Return the minimum number of jumps to reach the last index n-1. The test cases guarantee that the end is reachable.
Let's walk through an example:
nums = [2, 3, 1, 1, 4]
index: 0 1 2 3 4
- Starting at index 0 (value 2): you can jump to 1 or 2
- Optimal route:
0 → 1 → 4, only 2 jumps ✅ - Wrong route:
0 → 2 → 3 → 4, 3 jumps ❌
In an actual interview, align on three things before you open your mouth, and the interviewer will immediately know you're not reciting a memorized solution:
- You can jump at most
nums[i]steps; the landing point can be anywhere in that range — not necessarily the maximum. - The problem guarantees reachability; you don't need an unreachable fallback branch (but keep one in mind; follow-up questions will test it).
- It asks for the minimum steps, not the path, not "can you reach" (that's LeetCode 55).
💡 In real engineering, the same principle applies: starting to code without aligning on requirements costs the most rework. These three sentences take 30 seconds and give the interviewer the first impression of who you are.
2. Evolution of approach: from "can do" to "optimal" (this is what the interviewer wants to hear)
The interviewer doesn't want to hear "I memorized the answer" but how you optimized from brute force. The evolution path:
| Stage | Idea | Complexity | Interview impression |
|---|---|---|---|
| ① Brute-force backtracking | Try every step at each position, recursively search all paths | O(2^n) exponential | ❌ Only shows you understood the problem |
| ② Dynamic programming | dp[i] = min steps to i, relax the whole range |
O(n^2) / O(n) | ⭕ Passes, but not impressive |
| ③ BFS layered | Each jump = one layer, layer number = steps | O(n) / O(n) | ✅ Very intuitive |
| ④ Greedy compression | No queue, only two boundaries | O(n) / O(1) | 🏆 Optimal solution, key focus |
DP as a stepping stone (write it first, then optimize it away)
Define dp[i] as the minimum jumps to reach index i. For each i, relax the entire range it can jump to:
public int jumpDp(int[] nums) {
int n = nums.length;
int[] dp = new int[n];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for (int i = 0; i < n; i++) {
if (dp[i] == Integer.MAX_VALUE) continue;
for (int j = i + 1; j <= Math.min(n - 1, i + nums[i]); j++) {
dp[j] = Math.min(dp[j], dp[i] + 1);
}
}
return dp[n - 1];
}
O(n^2) time, O(n) space. With n up to 10^4 it barely passes, but the same range gets relaxed repeatedly, and that's the waste. The interviewer's next line will be: "Can you do better?"
The key leap: see each jump as one BFS layer
There's a crucial premise — every jump costs exactly 1. With equal cost, let each jump go as far as possible. That's greedy.
Change perspective: the 1st jump covers [0, 0], the 2nd jump starts from all positions the 1st jump can land on... each jump is a BFS layer, and the first time you hit the target, the layer number is the minimum steps. Because each layer covers a contiguous range of indices, you don't need an actual queue; two variables are enough:
| Variable | Meaning | Plain interpretation |
|---|---|---|
curEnd |
Right boundary covered by the current jump | The "red line" of this jump; keep scouting until the line is reached |
farthest |
Farthest index reachable by any landing point in the current layer | The farthest point the scout has explored |
steps |
Jumps taken | Number of key decisions made |
When the scan pointer i hits curEnd, you've seen every position in this layer and must jump: steps++, push the boundary to farthest.
🔥 One sentence to remember the greedy essence: Don't worry about where exactly to land; as long as you're within the current jump's covered range, record the farthest point you can reach. When you hit the boundary, decisively jump. Like playing Super Mario — you only care about two things: how far this jump can reach, and, before that, scout where the next jump could go.
3. Illustrated execution: walk through [2,3,1,1,4] by hand
We'll translate the trace.
index: 0 1 2 3 4
nums: [ 2, 3, 1, 1, 4 ] 🏁
initial: curEnd=0 farthest=0
🚀 Jump 1 (i = 0):
farthest = max(0, 0+2) = 2
i == curEnd(0) → jump! steps=1, curEnd=2
🚀 Jump 2 (i = 1, 2):
i=1: farthest = max(2, 1+3) = 4 ← scout finds treasure
i=2: farthest = max(4, 2+1) = 4
i == curEnd(2) → jump! steps=2, curEnd=4
curEnd(4) >= n-1(4) → reached target, finish early 🎉
Answer = 2 (path 0 → 1 → 4)
Then the variable flow table:
| i | nums[i] | farthest | i == curEnd ? | steps | curEnd |
|---|---|---|---|---|---|
| 0 | 2 | 2 | ✅ yes | 1 | 2 |
| 1 | 3 | 4 | ❌ no | 1 | 2 |
| 2 | 1 | 4 | ✅ yes | 2 | 4 (≥ n-1, end) |
And the decision flow diagram:
4. Core code (Java interview standard version)
class Solution {
public int jump(int[] nums) {
int n = nums.length;
if (n <= 1) return 0; // start is the end, 0 steps
int steps = 0; // jumps taken
int curEnd = 0; // right boundary of the current jump
int farthest = 0; // furthest reachable in the next jump
// ⚡ Note: i < n - 1, do not process the last element
for (int i = 0; i < n - 1; i++) {
// ① Keep scouting: within the current range, how far can the next jump go?
farthest = Math.max(farthest, i + nums[i]);
// ② Hit the current jump's boundary → must jump
if (i == curEnd) {
steps++;
curEnd = farthest;
// ③ Pruning: reached the target, finish early
if (curEnd >= n - 1) break;
}
}
return steps;
}
}
Complexity: ⏱️ O(n) one pass | 💾 O(1) three variables.
Layered BFS version (easier to explain and prove to the interviewer)
class Solution {
public int jump(int[] nums) {
int n = nums.length, jumps = 0, start = 0, end = 0;
while (end < n - 1) { // not covering the target yet, expand one layer
int farthest = 0;
for (int i = start; i <= end; i++) // only look at the current layer
farthest = Math.max(farthest, i + nums[i]);
start = end + 1; // left boundary of the next layer
end = farthest; // right boundary of the next layer
jumps++; // expanding one layer = one jump
}
return jumps;
}
}
⚠️ You must say this: It looks like nested loops, but the inner loop indices move monotonically forward; each index is visited only once, so the total work is still
n, amortized O(n). If you don't say this, the interviewer will think you wrote O(n^2). This also explains why you don't need an actual queue — each layer covers a contiguous range, and two pointers express the whole layer. It's an equivalent BFS with a smaller constant.
Four technical highlights in the code (volunteer these in the interview!)
i == curEndis the "implicit BFS layer switch". Standard BFS usesqueue.size()to control one layer; here "index equals boundary" replaces that, compressing space from O(n) to O(1) — compressing the BFS queue into two variables, that's the art of greedy.- Loop writes to
n - 1: The target doesn't need to be "jumped from". Even if you writei < n, the result is often correct, but that's saved by then = 1fallback and boundary luck — interviewers see through code that works by coincidence. You can say, "It's like I'm already at the target, so I don't need to take another step." steps++is tied to the "boundary event": It doesn't increment blindly in the loop; it only records after finishing a layer, naturally corresponding to BFS layer counting.- Early
break:curEnd >= n - 1means the remaining indices are meaningless to compute. For examplenums = [5,1,1,1,1], one step reaches the end; early exit saves time and is logically correct.
Also use semantic variable names (curEnd / farthest instead of a / b); readability is productivity.
5. Why is greedy correct? (The interviewer will likely ask)
Just saying "it feels like jumping farthest" gets you labeled as memorizing answers. Here are three explanations, any one is enough:
Explanation 1 · BFS view (easiest to understand). One jump = one BFS layer. The range the k-th jump covers, [L_k, R_k], is deterministic: R_k = max(i + nums[i]) for i ∈ [L_{k-1}, R_{k-1}]. No matter which specific point in the range you land on, the boundary that extends to the next layer is the same — so "where exactly you land" doesn't matter; what matters is how far the boundary can push. The BFS layer number by definition is the shortest path length; greedy is strictly equivalent to that, hence optimal.
Explanation 2 · Exchange argument. Suppose an optimal solution's first step lands on p, and the greedy's first step lands on q. The greedy rule guarantees that from q you can reach at least as far as from p. So replace the optimal's first step with q; the rest of the path still works, and the step count doesn't increase — greedy is no worse than the optimal, and it's feasible, so it's optimal.
Explanation 3 · Induction. Assume the farthest position reachable after k jumps is end_k, and the (k+1)-th jump's optimal starting point must be chosen from [0, end_k]. The farthest we maintain during the scan is exactly the optimal value of end_{k+1}. Each step is optimal, so the total steps are minimal.
🎁 Bonus sentence: This problem can be solved greedily because the cost of each jump is constant (1). Once the cost per jump differs (e.g., variable energy), greedy immediately fails; you must fall back to DP or Dijkstra's shortest path. Actively framing the algorithm's applicability conditions is a big plus.
6. Complexity comparison and benchmark data
| Solution | Time | Space | Interview positioning |
|---|---|---|---|
| 🥇 Greedy (forward scan) | O(n) | O(1) | First choice; write this directly |
| Greedy (layered BFS) | O(n) (amortized) | O(1) | Use to explain and prove |
| Real queue BFS | O(n) | O(n) | For understanding essence, larger constant |
| Dynamic Programming | O(n^2) | O(n) | Stepping stone to greedy |
| Reverse greedy | O(n^2) | O(1) | Only for verbal explanation, don't write |
| Brute-force backtracking | O(2^n) | O(n) | Mention once |
Local benchmark (JDK 17):
| Scenario | Greedy | DP |
|---|---|---|
n = 10^4, nums[i] = 1000 |
0.41 ms | 12.25 ms |
n = 10^7, nums[i] = 1000 |
10.2 ms | — (can't run) |
For the same n, about 30x difference; with n an order of magnitude larger, DP is out entirely. So when asked "Can you handle 10^5 data?", an O(n) single pass handles it easily.
7. Pitfall collection: these 8 pits I've stepped on for you
| # | Pit | Symptom | Correct approach |
|---|---|---|---|
| 1 | Loop end n vs n-1 |
Writing i < n makes i hit the last index and trigger i == curEnd again, counting one extra jump |
Fix i < n - 1: the last index is reached, no need to jump from it |
| 2 | Boundary trigger timing | Incrementing steps++ early over-counts; jumping late misses the whole layer |
Remember it as one event: only after all positions in this layer are seen can you jump |
| 3 | n = 1 degenerate input |
Loop can't get the correct answer | Add if (n <= 1) return 0; at the start (the loop condition is naturally correct, but writing it explicitly is safer) |
| 4 | nums[i] = 0 zombie cell |
Fear of getting stuck in place | Harmless here — boundary advances by farthest, not by nums[i]; but in problem 55 you must return false when i > maxReach |
| 5 | Initial boundary written incorrectly | curEnd = nums[0] |
curEnd = 0; the 0-th jump position is 0 |
| 6 | Integer overflow | i + nums[i] could theoretically overflow |
Write Math.min(n - 1, i + nums[i]), which also speeds up comparison |
| 7 | Layered version mistaken for O(n^2) | Outer while + inner for looks like double loop | Point out that the inner indices move monotonically forward; total visits remain n |
| 8 | Using greedy without thinking for variants | Wrong answer when costs are unequal | State explicitly: unequal costs → back to DP / Dijkstra; negative numbers also break greedy |
8. Difference from LeetCode 55 (must-know)
| Dimension | LeetCode 55 Jump Game I | LeetCode 45 (this problem) |
|---|---|---|
| Question | Can you reach the end? | What is the minimum jumps to reach the end? |
| Core | Maintain maxReach, check if i > maxReach |
Maintain curEnd + farthest, count layers |
| Termination | Early false |
Always reachable, return steps directly |
| Essence | Reachability | Optimality |
Volunteering this comparison in the interview makes the interviewer think you practice systematically, not by rote. Along this line, the same family:
| Problem | Title | Key difference |
|---|---|---|
| LC 55 | Jump Game I | Only reachability |
| LC 1306 | Jump Game III | Can jump forward/backward, BFS/DFS graph search |
| LC 1345 | Jump Game IV | Equal values allow teleport, BFS + hash grouping |
| LC 1871 | Jump Game VII | Sliding window + reachability |
| LC 403 | Frog Jump | DP + hash acceleration |
👋 Side note: I post this kind of interview-prep review every week; follow me and I'll walk you through the linked problems one by one.
9. Eight high-frequency follow-up questions (prepare in advance)
Q1: What if the problem doesn't guarantee reachability?
At i == curEnd, check whether farthest is farther than curEnd. If farthest == curEnd and i != n - 1, then the range can't expand any further; return -1. This tests your awareness of unreachable branches (it's also a fusion of 45 + 55).
Q2: What if you need to output the specific path?
For each layer, record a source index (like parent in BFS; record from while probing farthest), then backtrack from the target to the start. Space goes from O(1) to O(number of jumps).
Q3: Why not actually open a queue for BFS? Each jump covers a contiguous range of indices, so two pointers express the whole layer, saving queue operations and O(n) extra space. It's an equivalent BFS with a smaller constant.
Q4: Can it be optimized further?
You can't go below O(n). Each element must be looked at at least once, otherwise the information in nums[i] isn't fully used. O(n) is the lower bound.
Q5: What if the array is all 1s?
The answer is n - 1; each jump can only move one step. This is a degenerate case for greedy; the code doesn't need special handling and still works.
Q6: Change to "count the number of paths to the target"?
Greedy fails; it becomes DP: dp[i] = Σ dp[j] (for all j that can reach i), O(n^2). Because the question changes from "find optimal" to "count".
Q7: The array is huge and comes as a stream?
Still only O(1) state; update farthest and curEnd as you read. It naturally supports streaming — this is an engineering advantage of greedy over DP.
Q8: Is there a reverse greedy? Yes, from right to left, maintain the leftmost position that can reach the current target. Also O(n), but forward is more intuitive and easier to explain.
10. Interview practical tips
Recommended opening (memorize):
"Alright, interviewer. Let me restate the problem: the goal is the minimum number of jumps, not whether we can reach. Since we're guaranteed reachable, my first thought is greedy, O(n) time O(1) space. Let me first mention the brute-force idea, then show how to optimize to greedy, okay?"
This opening reveals the complexity card and sets the rhythm.
Closing script (after finishing the code):
"In summary, this problem's core is to replace point-by-point decision with 'interval boundaries': delay the decision and trigger on boundary — don't rush to decide where to jump; when you must jump, base it on the farthest boundary you've scouted. Time O(n), space O(1). Correctness can be shown via BFS layering or exchange argument."
If you can draw the alternating updates of curEnd and farthest on the whiteboard while explaining, and write out the two optimizations n - 1 and break, this problem is basically a Strong Hire level.
One-minute memorization:
- One-sentence model: one jump = one BFS layer;
curEndis the current layer's right boundary,farthestis the next layer's right boundary - Two actions: update
farthestas you scan; whenihitscurEnd,steps++and push the boundary tofarthest - Three details:
n <= 1returns 0 directly; loop ton - 1; early break when reaching the end - One complexity pair: O(n) / O(1)
- One bonus sentence: greedy holds only because each jump costs 1; when costs differ, go back to DP
Self-review checklist:
- Can you verbally walk through
[2,3,1,1,4]without looking at code? - Can you explain why
i < n - 1instead ofi < n? - Can you prove greedy correctness with BFS layering or exchange argument?
- Can you say why the layered version is amortized O(n)?
- Do you know the difference in handling
nums[i] = 0between problem 45 and 55? - Can you proactively say "greedy fails when jump costs differ"?
- Can you write the code correctly on a whiteboard with no boundary omissions?
Final words
The essence of this problem is not "jump farthest every step", but find the point that makes the next step's view the farthest within the current view — the key to avoiding detours is to see far, not to run fast. One piece of practical advice: don't just accept one AC and move on. Go through the proof and follow-up questions with the checklist above to truly own this problem (the code has been tested locally on JDK 17, passing 6 sets of samples, and randomly compared against DP on 130,000+ cases with consistent results).
Leave an interaction: Which "seemingly simple but full of pitfalls" problem have you been ambushed by in an interview? Comment the problem number, the one with the most likes, I'll break it down next week with the same thoroughness. If you find it useful, click "like + share" and forward it to your comrades who are practicing. See you next time 👋