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
- Track the farthest index we can reach
- At each position i, update: maxReach = max(maxReach, i + nums[i])
- If we can't reach position i (i > maxReach), return false
- If maxReach >= last index, return true
Related Data Structures & Algorithms exercises
- Practice Word Ladder (Shortest Path) in Java
- Practice Rotting Oranges (Multi-source BFS) in Java
- Practice Activity Selection (Interval Scheduling) in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler