Jump Game
Difficulty: Medium · Pattern: Greedy · LeetCode #55
You start at index 0. From index i you may jump up to nums[i] positions forward. Return true if you can reach the last index.
Examples
text
nums = [2, 3, 1, 1, 4] → true
nums = [3, 2, 1, 0, 4] → false (every path lands on the 0 at index 3)
nums = [0] → true (already at the end)Hints
- You don't need to know the exact path, only how far you could possibly get.
- Maintain
reach= the farthest index reachable so far. If you ever stand at an index beyondreach, you're stuck.
Approach
Scan left to right with reach = 0. At index i, if i > reach, index i is unreachable, so return false. Otherwise update reach = max(reach, i + nums[i]). If reach ≥ n − 1, return true. Stays-ahead: reach is exactly the set of reachable indices' upper bound, since every index ≤ reach is reachable.
Complexity
Time: O(n). Space: O(1).
Python solution
def canJump(nums):
reach = 0
for i, x in enumerate(nums):
if i > reach:
return False
reach = max(reach, i + x)
if reach >= len(nums) - 1:
return True
return TrueJavaScript solution
function canJump(nums) {
let reach = 0;
for (let i = 0; i < nums.length; i++) {
if (i > reach) return false;
reach = Math.max(reach, i + nums[i]);
if (reach >= nums.length - 1) return true;
}
return true;
}