Jump Game Algorithm
You have an array of integers. You start at index 0. Each number tells you the maximum distance you can jump forward from that position.
28 Mar 2024

You have an array of integers. You start at index 0. Each number tells you the maximum distance you can jump forward from that position.
Can you reach the last index?
Input: nums = [2,3,1,1,4]
Output: true
Jump 1 step from index 0 to 1, then 3 steps to the last index.
The intuition
Think of it like crossing a river on stepping stones. At each stone, you can see how far you're allowed to leap. You don't need to find the exact path. You just need to know: is the end reachable at all?
The trick is to track the farthest position you can reach as you walk through the array. If you ever land on a position beyond your farthest reach, you're stuck. If your farthest reach covers the last index, you're done.
One pass. No backtracking.
The code
const canJump = function(nums) {
if (nums.length <= 1) {
return true;
}
let maxReach = 0;
for (let i = 0; i < nums.length; i++) {
if (i > maxReach) return false;
maxReach = Math.max(maxReach, i + nums[i]);
if (maxReach >= nums.length - 1) return true;
}
return false;
};
How it works
Walk through the array left to right. At each index, update the farthest position you could possibly reach. If your current index ever exceeds that farthest reach, return false — you're stranded. If the farthest reach passes the last index, return true early.
Complexity
- Time: O(n) — single pass through the array.
- Space: O(1) — just one variable tracking the max reach.
Trade-offs
This greedy approach is simple and fast. But it only answers "can you reach the end?" If you need the actual path or the minimum number of jumps, you'll need a different strategy — BFS or dynamic programming.