Algorithms · Visualized
Jump Game
Greedy
Make the locally optimal choice at each step, hoping it leads to a globally optimal solution.
Given an array where each element represents the maximum jump length from that position, determine if you can reach the last index starting from the first. Time: O(n) average, O(n) worst; space: O(1).
Big-O: Works when the problem has optimal substructure + greedy-choice property — e.g. intervals, Huffman, fractional knapsack.
Jump Game
GreedyGiven an array where each element represents the maximum jump length from that position, determine if you can reach the last index starting from the first. The greedy approach tracks the farthest index reachable so far as you scan left to right — if you ever reach a position beyond the farthest reachable point, you're stuck.
How Jump Game Works
- Track 'farthest', the furthest index reachable so far, starting at 0.
- Loop through the array from left to right, using the current index i.
- If i is greater than 'farthest', you can't reach this position at all — return false immediately.
- Update 'farthest' to the maximum of its current value and (i + array[i]) — the reach from this position.
- If 'farthest' reaches or exceeds the last index at any point, return true.
Jump Game Worked Example
Input: [2, 3, 1, 1, 4]
farthest=0. i=0: 0≤0 ok, farthest=max(0,0+2)=2. i=1: 1≤2 ok, farthest=max(2,1+3)=4. Since farthest(4) ≥ last index(4), reachable — return true immediately.
def jump_game(a):
reach = 0
for i, v in enumerate(a):
if i > reach:
return False
reach = max(reach, i + v)
return TrueBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Jump Game Time & Space Complexity
When to Use Jump Game
- Reachability analysis in games (can a character reach a goal given movement limits per tile?).
- Network hop-reachability: can a signal/packet reach a destination given per-node max range?
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.