Greedy Algorithms · Array · Farthest reach

Jump Game Visualizer

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

Every possible jumpFrom each index, branch on every legal landing spot. The same index is reached by many paths, so the recursion tree is exponential.
Farthest reachScan left to right and remember only the farthest index you can touch. If the scan walks past that index, every earlier jump has already been considered and the end is impossible. If farthest covers the last index, stop.

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.

Every legal jump

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.

def can(i):
if i >= n - 1: return true
for step in 1 .. nums[i]:
if can(i + step): return true
return false
Step 0 Answer —

Greedy visualization

Step through the greedy choice

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.

far = 0
for i = 0 to n - 1:
if i > far: return false
far = max(far, i + nums[i])
if far >= n - 1: return true
return true
Step 0 Answer —

Complexity

PieceCostWhy
TimeO(n)Each index is visited once.
SpaceO(1)Only the farthest index is stored.
Greedy choiceMax reachA shorter jump cannot open an index this reach missed.

Implementation

def can_jump(nums): far = 0 for i, jump in enumerate(nums): if i > far: return False far = max(far, i + jump) if far >= len(nums) - 1: return True return True