Jump Game – Solution & Complexity
Watch: Jump Game by tracking the farthest reach
Always taking the biggest jump fails: on 2, 5, 0, 0 a jump of 2 lands on a 0, but a jump of 1 onto the 5 clears the end. Don't choose jumps at all. Walk left to right and keep far, the farthest index reachable so far: index 0 reaches 2, index 1 reaches 6, which covers the last index, so true. On 3, 2, 1, 0, 4 every spot reaches only index 3, and index 4 is past far, so false. O(n) time, O(1) space.
Solution Walkthrough
Step 1: Understand Reachability
- Each value tells you the maximum jump length from that index.
- You only need to know whether the last index can be reached, not the exact path.
- If you ever stand beyond the farthest reachable index, progress is impossible.
Step 2: Brute Force or DP Idea
- One approach marks which indices are reachable from earlier indices.
- For every reachable index, mark all destinations within its jump range.
- This can work, but it may take O(n²) time in large arrays.
Step 3: Track the Farthest Reach
- A greedy scan is enough because jumps only move forward.
- Maintain
farthest, the greatest index reachable so far. - At each reachable index, update
farthestwithi + nums[i].
Step 4: Detect Failure or Success
- If the current index is greater than
farthest, there is no way to reach it, so returnFalse. - If
farthestreaches or passes the last index, returnTrue. - Otherwise continue scanning reachable positions.
- If the current index is greater than
Step 5: Final Complete Solution
- The greedy invariant is that all indices up to
farthestare reachable while scanning. - Time complexity is O(n) because each index is visited once.
- Space complexity is O(1).
- The greedy invariant is that all indices up to