Jump game and gas station
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Reachability and circular tour problems can be solved in linear time by tracking running boundaries greedily.
Jump Game I: Farthest reach in linear time
In the jump game, each index contains a maximum forward jump length. The goal is determining whether the last index is reachable from index zero. Brute force recursion tries every jump choice, taking exponential time.
Step by step
Step 1 of 4
- maxReach
- 2
- index
- 0
Example 1 · Brute force: try every jump length recursively, O(2^n)
public class Main { static boolean canReach(int[] nums, int i) { if (i >= nums.length - 1) return true; for (int step = 1; step <= nums[i]; step++) { if (canReach(nums, i + step)) return true; } return false; }
public static void main(String[] args) { int[] a1 = {2, 3, 1, 1, 4}; int[] a2 = {3, 2, 1, 0, 4}; System.out.println("Can reach a1: " + canReach(a1, 0)); System.out.println("Can reach a2: " + canReach(a2, 0)); }}Can reach a1: true Can reach a2: false
What this code does
- From each index it tries every allowed jump length, one after another.
- The same index is reached again and again through different routes, so the work can double with each position.
- The next example remembers each answer instead of repeating it.
Example 2 · Better: mark reachable positions, O(n^2) time, O(n) space
public class Main { static boolean canJump(int[] nums) { boolean[] reach = new boolean[nums.length]; reach[0] = true; for (int i = 0; i < nums.length; i++) { if (!reach[i]) continue; for (int step = 1; step <= nums[i] && i + step < nums.length; step++) { reach[i + step] = true; } } return reach[nums.length - 1]; }
public static void main(String[] args) { int[] a1 = {2, 3, 1, 1, 4}; int[] a2 = {3, 2, 1, 0, 4}; System.out.println("Can reach a1: " + canJump(a1)); System.out.println("Can reach a2: " + canJump(a2)); }}Can reach a1: true Can reach a2: false
What this code does
- Each position is marked once and never explored twice, which removes the repeated recursion.
- Marking the jump range from every reachable index still costs O(n) per index.
- Only the farthest reach matters, so one number replaces the whole array.
Example 3 · Optimal: track the farthest reach, O(n) time, O(1) space
public class JumpGameCanReachDemo { public static boolean canJump(int[] nums) { int maxReach = 0; for (int 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 true; }
public static void main(String[] args) { int[] a1 = {2, 3, 1, 1, 4}; int[] a2 = {3, 2, 1, 0, 4}; System.out.println("Can reach a1: " + canJump(a1)); System.out.println("Can reach a2: " + canJump(a2)); }}Can reach a1: true Can reach a2: false
What this code does
- Tracks maxReach as the farthest reachable index so far.
- Array a1 reaches the end because index 1 extends reach to index 4.
- Array a2 gets stuck at index 3 because value 0 prevents advancing.
- One number, maxReach, replaces the array of reachable positions, so a single pass is enough.
A greedy approach tracks a single variable called farthest reach. At each index, verify whether the current position is reachable. If the current index exceeds the farthest reach, you are stuck. Otherwise, update the farthest reach with index plus jump length. If the farthest reach meets or exceeds the final index, return true. This linear scan finishes in constant auxiliary space.
Find the bug
Spot the Jump Game bug
Select the line that is wrong.
If position i cannot be reached, the answer is false.
Round 1 of 2Jump Game II: Minimum jumps as greedy breadth search
Jump Game II asks for the minimum jump count to reach the end. We can view this problem as a breadth-first search along an array. Each jump explores all indices reachable within the current boundary.
Example 4 · Minimum Jumps to Reach End
public class JumpGameMinJumpsDemo { public static int jump(int[] nums) { if (nums.length <= 1) return 0; int jumps = 0; int currEnd = 0; int farthest = 0;
for (int i = 0; i < nums.length - 1; i++) { farthest = Math.max(farthest, i + nums[i]); if (i == currEnd) { jumps++; currEnd = farthest; if (currEnd >= nums.length - 1) break; } } return jumps; }
public static void main(String[] args) { int[] nums = {2, 3, 1, 1, 4}; System.out.println("Minimum jumps: " + jump(nums)); }}Minimum jumps: 2
What this code does
- From index 0, jump 1 covers up to index 2 (currEnd = 2).
- Within range [0, 2], index 1 offers farthest reach to index 4.
- When reaching currEnd at index 2, jump 2 advances currEnd to index 4.
Track two boundary pointers called current end and farthest reach. Iterate through the array up to the second-to-last element. At each step, update farthest with index plus jump distance. When the loop index reaches current end, a jump must be made. Increment the jump counter and advance current end to farthest. This simulates queue-based level exploration without allocating memory.
Gas Station: Total deficit and circular start reset
The gas station problem checks if a circular car journey is possible. Station i provides gas[i] fuel and requires cost[i] to reach station i + 1. Brute force tests starting from every station, requiring quadratic time.
Example 5 · Brute force: simulate the loop from every start, O(n^2)
public class Main { static int canCompleteCircuit(int[] gas, int[] cost) { int n = gas.length; for (int start = 0; start < n; start++) { int tank = 0; int steps = 0; while (steps < n) { int i = (start + steps) % n; tank += gas[i] - cost[i]; if (tank < 0) break; // ran out before the next station steps++; } if (steps == n) return start; } return -1; }
public static void main(String[] args) { int[] gas = {1, 2, 3, 4, 5}; int[] cost = {3, 4, 5, 1, 2}; System.out.println("Starting station: " + canCompleteCircuit(gas, cost)); }}Starting station: 3
What this code does
- Each possible start drives around the circle until the tank goes negative or the lap ends.
- Failed starts still cost up to n steps each, so the total is O(n^2).
- The greedy pass skips every start that lies inside a failed stretch, so it needs one lap.
Example 6 · Optimal: one lap with a running tank, O(n) time, O(1) space
public class GasStationTourDemo { public static int canCompleteCircuit(int[] gas, int[] cost) { int totalTank = 0; int currTank = 0; int start = 0;
for (int i = 0; i < gas.length; i++) { int diff = gas[i] - cost[i]; totalTank += diff; currTank += diff; if (currTank < 0) { start = i + 1; currTank = 0; } } return totalTank >= 0 ? start : -1; }
public static void main(String[] args) { int[] gas = {1, 2, 3, 4, 5}; int[] cost = {3, 4, 5, 1, 2}; System.out.println("Starting station: " + canCompleteCircuit(gas, cost)); }}Starting station: 3
What this code does
- Net fuel changes: [-2, -2, -2, +3, +3]. Total surplus is 0.
- Deficit at stations 0, 1, and 2 resets candidate start to station 3.
- Starting at station 3 allows completing the full circular route.
- When the tank goes negative, no start inside that stretch can work, so the next candidate is the next station and nothing is re-simulated.
First, check total gas versus total cost across all stations. If total gas is less than total cost, completing the circuit is impossible. If total gas meets or exceeds total cost, a solution is guaranteed. Track current tank fuel while scanning from station zero. If the tank drops below zero at station i, station zero cannot reach station i + 1. Furthermore, no station between zero and i could reach i + 1 either. Reset start to i + 1 and reset current tank to zero.
Next step
Check your understanding
10 quick questions