Jump Game in Java: Explanation & Practice

Can you reach the last index?

Problem summary

Given an array where each element represents max jump length at that position, determine if you can reach the last index starting from index 0.

Starter code

public class Main {
    public static void main(String[] args) {
        int[] nums = {2, 3, 1, 1, 4};
        
        // Greedy: track farthest reachable position
        // At each step: maxReach = max(maxReach, i + nums[i])
        // If i > maxReach, we're stuck
        // Print: Can reach: true
    }
}

Expected output and test cases

  • [2,3,1,1,4]
    Can reach: true
  • [3,2,1,0,4]
    Can reach: false
  • [0] → already at end
    Can reach: true

Hints

  1. Track the farthest index we can reach
  2. At each position i, update: maxReach = max(maxReach, i + nums[i])
  3. If we can't reach position i (i > maxReach), return false
  4. If maxReach >= last index, return true

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler