Jump Game
Problem Statement
You’re a jumper in an array where each element represents the maximum jump length from that position. Starting at index 0, determine if you can reach the last index. This medium-level greedy problem is all about stretching your leaps to cover the distance—can you make it to the end?
Example
Input: nums = [2, 3, 1, 1, 4]
Output: true (0→1→4 reaches the end)
Input: nums = [3, 2, 1, 0, 4]
Output: false (stuck at index 3 with jump 0)
Code
Java
Python
JavaScript
public class Solution {
public 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;
}
}
def can_jump(nums):
max_reach = 0
for i in range(len(nums)):
if i > max_reach:
return False
max_reach = max(max_reach, i + nums[i])
if max_reach >= len(nums) - 1:
return True
return True
function canJump(nums) {
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 true;
}
Explanation
- Greedy Choice: Track the farthest reachable index at each step.
- Flow: If current index exceeds max reach, fail; otherwise, update max reach.
- Example: [2,3,1,1,4] → maxReach=2, 4, 4, 4, 4 (reaches end).
Note
Time complexity: O(n), Space complexity: O(1). A simple greedy leap to victory!
