Jump Game
Decide whether the last index is reachable by tracking the farthest index any reachable position can jump to.
Watch it animatedStep through it, with the running line highlighted. Free with an account.The idea
Every index up to farthest is reachable: you can always jump a shorter distance than the maximum. Walk left to right; from each reachable index i you could land anywhere up to i + nums[i], so stretch farthest to that. If the walk ever reaches an index beyond farthest, no earlier index can get there and you are stuck. If farthest covers the last index, you are done.
Code
public static bool CanJump(int[] nums) {
int farthest = 0;
for (int i = 0; i < nums.Length; i++) {
if (i > farthest) return false;
farthest = Math.Max(farthest, i + nums[i]);
if (farthest >= nums.Length - 1) return true;
}
return false;
}Tips
- A 0 is only a trap if farthest has not already passed it: try 2, 0, 2, 0, 1, 0, 3 (index 6 is out of reach) against 2, 3, 1, 1, 4 (reaches the end).
- You never need to know WHICH jumps to take, only how far the reachable prefix extends, so there is no backtracking or DP table.
- Jump Game II (fewest jumps) uses the same idea level by level: the current reach window is one jump, the farthest reach from it is the next window.
In the .NET library
Math.Max keeps the loop branch-free; the early return true matters on long inputs where the first few elements already reach the end.