What is Jump Game
You are given an integer array nums. You start at index 0. From index i you may jump forward any distance from 1 up to nums[i]. Return true when some sequence of jumps lands on the last index.
Example 1. nums = [2, 3, 1, 1, 4] returns true. One route is index 0, then 1, then 4.
Input: 2 3 1 1 4 Output: true
Example 2. nums = [3, 2, 1, 0, 4] returns false. Index 3 has a jump of 0, and no earlier jump can land beyond it.
Input: 3 2 1 0 4 Output: false
Constraints. 1 ≤ n ≤ 104, and each jump length is non-negative. This visualizer keeps n at 12 so the reach bar stays readable.
Approach
Brute force recursion tree
From index i, try every jump of length 1 through nums[i]. The call can(i + step) asks whether that landing spot can reach the end. The same index is reached by many parents, so the tree is exponential. A working program may stop at the first true child. This picture keeps every branch so the repeated calls are visible.
The finished tree is shown first. Next and Play start the walk again from the first call. Keep the array at 5 indexes or fewer.
Greedy visualization
The walk starts on the first pseudocode line. Next and Play move one step at a time, and the highlighted line is the line that just ran.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each index is visited once. |
| Space | O(1) | Only the farthest index is stored. |
| Greedy choice | Max reach | A shorter jump cannot open an index this reach missed. |
Implementation