Given an array where each element is the maximum jump length from that position, print true if you can reach the last index starting from index 0.
Example
Input: 2 3 1 1 4
Output: true
Approach
Track the farthest index reachable so far. Walk through the array once: if the current index is already beyond the farthest reachable point, you can never get here, so it's impossible. Otherwise, update the farthest reachable point using this position's jump length. No need to try every possible jump combination — the single running "farthest reachable" value is sufficient.
Walkthrough
python
1reach = 0
2for i, n in enumerate(nums):
3 if i > reach:
4 return False
5 reach = max(reach, i + n)
6return True
Step 1 / 5
i=0 is within reach (reach starts at 0) — extend reach using this position's jump length: max(0, 0+2)=2.
Input format
Line 1: the array, space-separated
Print true or false.
Not solved yet
Ctrl+Enter
Editor
nums = list(map(int, input().split()))
# TODO: track the farthest reachable index as you scan left to right
reach = 0for i, n inenumerate(nums):
pass
Input (stdin)
Output
Run your code to see output here.
Isolated sandbox · not executed on your devicePowered by Judge0 CE (free, self-hosted). Runs in an isolated sandbox — not on your device.
Editor
nums = list(map(int, input().split()))
# TODO: track the farthest reachable index as you scan left to right
reach = 0for i, n inenumerate(nums):
pass
Input (stdin)
Output
Run your code to see output here.
Isolated sandbox · not executed on your devicePowered by Judge0 CE (free, self-hosted). Runs in an isolated sandbox — not on your device.