public boolean canJump(int[] nums) { int goal = nums.length - 1; for (int i = nums.length - 1; i >= 0; i--) { if (i + nums[i] >= goal) { // i can hop onto the goal goal = i; } } return goal == 0;}
- i
- —
- nums[i]
- —
- i + nums[i]
- —
- goal
- —
Why it works
- Brute force tries every jump length from every index, recursively: exponential without memo, O(n²) as a DP table of "can index i reach the end?".
- Only the leftmost good index matters. Walk from the end.
goalis the leftmost index known to reach the last one. Indexiis good if it can hop ontogoal: anything pastgoalthaticould reach is reachable fromgoalanyway. - One sweep, one number: each index is checked once against
goal, so O(n) time and O(1) space. - Pitfall: use
>=, not>. A jump that lands exactly ongoalcounts, and a0sitting on the last index never matters, because you only need to land there. - Forward version: track the farthest reachable index while scanning left to right, and fail the moment
ipasses it. Jump Game II (45) extends that window idea to count the jumps.