AlgoTales · Roadmap

Jump game

Intermediate · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

The jump game asks whether you can reach the end of a row of steps when each step tells you the longest jump you can make from it. You just track the farthest place reachable so far and see if it ever falls short of where you are.

Practical use cases

  • Web app: Can a level be finished in a platform game. A browser game generator creates levels with platforms and maximum jump distances. A quick check tracks the farthest reachable platform and rejects any level where the player cannot get across, before it reaches players. Designers get an instant red flag in the editor and no longer need to test every level by playing it.
  • Web app: Multi-step form or wizard flow. A checkout wizard lets certain answers skip up to some number of steps. A validator checks that from the first screen the last confirmation screen is always reachable, so no user is stuck. It also catches broken skip rules early, before a real customer gets stuck on a screen with no way forward.
  • Web app: Network hop planner. A tool plans hops between relay points where each can forward up to some distance. The farthest-reach check tells whether a message can get from the first relay to the last.
  • System: Travel planning and interviews. Itinerary tools use this to see if a trip with limited hop lengths reaches a destination, and the puzzle is a common coding interview question. The single "farthest reach" number is all that needs to be remembered, which is why the code is only a few lines long.

The story: Kabir Crosses the River

The monsoon had flooded the lane near Grandpa Bhaskar's house, leaving a line of flat stones across the water. Kabir stood on the first stone. Each stone had a number painted on it, the longest jump he could make from there. A 3 means he could hop 1, 2, or 3 stones ahead.

Kabir wanted to cross to the far stone. He first tried every combination of hops and got dizzy; there were too many. Then Mira said: "Forget the exact path. Just keep track of the farthest stone you could ever reach."

Standing on stone 0 with power 3, the farthest reach is stone 3. At stone 1, power 2 would reach stone 3. Nothing new. Stone 2, power 1: reaches 3. Stone 3, power 0: still 3. Then stone 4 comes. But it is beyond the farthest reach of 3! Kabir could not step there, no matter how cleverly he hopped.

The greedy idea is tiny: while walking over the stones you can reach, always update the farthest reach. If you ever stand on a stone beyond the reach, stop, because the river cannot be crossed. If reach touches the last stone, the answer is yes. That is the jump game.

How to spot this problem, and where you need it

You have a series of positions where each says how far you can move forward, and you need a fast yes or no for whether you can reach the end, or the fewest jumps needed.

Signs you need it

  • The input is an array where each number means "maximum steps you may take from here".
  • The wording is "can you reach the last index" or "minimum number of jumps".
  • A recursive try-everything solution becomes very slow for long arrays.

Where to use it in a project

  • Level validators in game generators and level editors, run before a level is published.
  • Flow validators in multi-step forms, onboarding tours and wizards with skip rules.

The solution

Keep one number, farthest, starting at 0. Go through positions left to right. If the current position is bigger than farthest, you are stuck, so the answer is no. Otherwise update farthest to the larger of itself and position plus the jump length. If farthest reaches or passes the last position, the answer is yes. One pass, no guessing.

Payoff: Before: trying every jump combination, exploding for 50 platforms. After: a single scan of 50 numbers gives yes or no instantly.

Explain it like I am 8

Like hopping across stepping stones: you do not need to plan every hop. Just keep a mental flag at the farthest stone you could get to. If the next stone is further than your flag, you are stuck. If your flag reaches the end, you can cross!

How it works, step by step

  1. Keep a number reach, the farthest index you can get to. Start with 0.
  2. Walk through the stones one by one with index i.
  3. If i > reach, this stone cannot be reached: return false.
  4. Otherwise update reach = max(reach, i + nums[i]).
  5. If you finish the loop (or reach covers the last index), return true.

The code in four languages

PHP

<?php
// nums[i] = the longest jump allowed from stone i. Can we reach the last stone?
function canJump(array $nums): bool {
    $reach = 0;                              // farthest stone we can get to so far
    for ($i = 0; $i < count($nums); $i++) {
        if ($i > $reach) return false;       // this stone is out of reach
        $reach = max($reach, $i + $nums[$i]);
    }
    return true;
}

echo json_encode(canJump([2, 3, 1, 1, 4])) . PHP_EOL;   // true
echo json_encode(canJump([3, 2, 1, 0, 4]));              // false

JavaScript

// nums[i] = the longest jump allowed from stone i. Can we reach the last stone?
function canJump(nums) {
  let reach = 0;                             // farthest stone we can get to so far
  for (let i = 0; i < nums.length; i++) {
    if (i > reach) return false;             // this stone is out of reach
    reach = Math.max(reach, i + nums[i]);
  }
  return true;
}

console.log(canJump([2, 3, 1, 1, 4]));   // true
console.log(canJump([3, 2, 1, 0, 4]));   // false

Java

public class Main {
    // nums[i] = the longest jump allowed from stone i. Can we reach the last stone?
    static boolean canJump(int[] nums) {
        int reach = 0;                              // farthest stone we can get to so far
        for (int i = 0; i < nums.length; i++) {
            if (i > reach) return false;            // this stone is out of reach
            reach = Math.max(reach, i + nums[i]);
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(canJump(new int[]{2, 3, 1, 1, 4}));   // true
        System.out.println(canJump(new int[]{3, 2, 1, 0, 4}));   // false
    }
}

Go

package main

import "fmt"

// canJump: nums[i] = the longest jump allowed from stone i. Can we reach the last stone?
func canJump(nums []int) bool {
	reach := 0 // farthest stone we can get to so far
	for i, n := range nums {
		if i > reach { // this stone is out of reach
			return false
		}
		reach = max(reach, i+n)
	}
	return true
}

func main() {
	fmt.Println(canJump([]int{2, 3, 1, 1, 4})) // true
	fmt.Println(canJump([]int{3, 2, 1, 0, 4})) // false
}

Time: O(n) · Extra space: O(1). One walk over the stones and a single number, <code>reach</code>.

Watch out for

  • Trying all jump combinations (exponential) when one running maximum is enough.
  • Treating a jump number as an exact jump length. It is the maximum, so any shorter hop is allowed too.
  • Forgetting the check i > reach before using stone i.

Quick check

  1. What single value do we track?
    • The number of jumps so far
    • The farthest index reachable so far
    • The sum of all numbers
  2. For [3, 2, 1, 0, 4], why is the answer false?
    • The first number is too big
    • The array is too short
    • Reach gets stuck at index 3 because that stone has power 0
  3. What is the time complexity?
    • O(n)
    • O(n²)
    • O(2ⁿ)