Problem Statement
You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.
Return true if you can reach the last index, or false otherwise.
Approach: Maximum ReachABLE
Instead of exploring every possible jump (Backtracking $O(2^n)$), we track the furthest index we can currently reach.
- Iterate: Loop through the array.
- Unreachable: If the current index
i > maxReach, it means we can't get here. Returnfalse. - Update:
maxReach = max(maxReach, i + nums[i]). - Success: If
maxReach >= lastIndex, returntrue.
Java Implementation
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;
}
Complexity Analysis
- Time Complexity: $O(n)$. We pass through the array once.
- Space Complexity: $O(1)$.
Interview Tips
- Mention that this problem can also be solved with DP, but Greedy is the optimal $O(1)$ space solution.