Jump Game II: The Two-Variable Greedy That Beats DP by 30x, With Proofs and Interview Traps
The uniform-cost greedy for interval jumps appears in interviews at ByteDance, Tencent, and Kuaishou. Understanding why a two-pointer scan is optimal, with three independent proofs and the exact pitfalls, transfers to any range-minimization problem and gives a concrete edge in interview prep.
LeetCode 45 asks for the fewest jumps to reach the last index of an array, where each element is the maximum forward distance you can jump (you may jump less). The guaranteed-reachable case turns this into a classic greedy: with each jump costing exactly one step, the optimal move is to extend your reach as far as possible within the current jump. The standard solution keeps two variables: curEnd, the rightmost index the current jump can cover, and farthest, the furthest any cell inside that range can reach. As the scan moves left to right, farthest updates continuously; when i catches up to curEnd, the scan has exhausted the current jump's options, so it increments the step count and pushes curEnd to farthest. This runs in O(n) time and O(1) space.
The derivation starts with brute-force backtracking, which explodes exponentially, then moves through DP's O(n^2) relaxation, and finally lands on a BFS layered view: each jump corresponds to a layer, and because every jump costs 1, the first time a layer covers the target gives the minimum jumps. That view justifies the greedy because each layer covers a contiguous range, so two pointers replace the queue. Correctness is argued three independent ways: BFS layering, an exchange argument, and induction. The subtle loop bound (i < n-1) gets a precise explanation, nums[i]=0 is harmless here but fatal in Jump Game I, and early termination plus overflow handling are covered.
Benchmarks on JDK 17 show the greedy takes 0.41 ms for n=10^4 versus 12.25 ms for DP, and for n=10^7 the greedy finishes in 10.2 ms while DP cannot even run. Eight common pitfalls are enumerated, from loop bounds to initialization mistakes. Eight follow-up questions prepare candidates for real interviews, including path reconstruction, streaming input, and counting paths, where greedy no longer applies. A one-minute memorization cheat sheet and a self-review checklist close out the analysis.
The article's strongest point is isolating the uniform-cost assumption; that's the precise reason greedy holds. Many tutorials skip it, and this one explicitly warns that varying costs break the approach.
Turning a queue-based BFS into two pointers is a clean illustration of how constant-space optimizations preserve semantics when the search range is contiguous.
The bundled follow-up questions turn a coding solution into an interview rehearsal, which is more valuable than the code itself for passing big-tech loops.
The benchmark showing a 30x gap plus DP's inability to scale to 10^7 makes a practical case for choosing greedy, not just a theoretical one.