Example 1
- Input
- nums = [2, 3, 1, 1, 4]
- Output
- true
Jump one step from index 0 to 1, then three steps to index 4. The first jump need not use the full value 2.
Given an array where each element caps how far you can jump forward from that position, decide whether the last index is reachable starting from the first index.
Given a nonempty integer array nums, start at index 0. From index i, you may jump forward by any number of positions from 1 through nums[i]; the value is a maximum, not a required distance. Return whether you can reach the last index. You need not return a path or minimize the number of jumps.
Jump one step from index 0 to 1, then three steps to index 4. The first jump need not use the full value 2.
Indices 0, 1, and 2 can reach at most index 3. Its zero cannot extend reachability, so index 4 stays unreachable.
The starting index is already the last index; no jump is required even though the only value is zero.
Index 0 jumps directly to index 2, skipping the zero at index 1. A zero alone does not imply failure.
Reachable positions form a continuous prefix because any jump distance up to the maximum is allowed. In Example 1, index 0 with value 2 makes indices 1 and 2 reachable; reachable index 1 then extends that prefix through index 4. We can either explore the choices and remember each result, or merge every reachable choice into one farthest frontier. A zero blocks progress only when no earlier reachable position can jump past it.
Reveal Memoized Recursion: intuition, complexity, and code
[0], which starts on the goal and returns true.[2, 0, 0], which still returns true.[3, 2, 1, 0, 4], which returns false.[0, 100000] must return false. Check the gap before extending the frontier.[2, 0, 0] succeeds because an earlier jump bypasses it.When reachability only expands, maintain the frontier as one number and let each position extend it.