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.
Production-Ready Systems with LLMs and Agents
A live Maven cohort, 5 October to 2 November: eight 90-minute sessions where you build LLM and agent systems that survive real traffic, real cost and real failure. Tuesdays and Thursdays, 7:30 to 9:00pm London.
Cohort 2 starts 5 October. Eight live sessions, $1,500.
View the live cohortKeep reading
- The Algorithms Worth Knowing in Code Review: Cutting Big O Without Being Clever
- Tracking Down the Mystery: Finding the Unique Delivery ID
- Elusive Least Occurring Number in an Array
- Solving the Height of a Binary Tree Puzzle
- Harry Potter Discounts: A Code Challenge Algorithm
- Implementing a Task Heap Service in TypeScript