Algorithms · Visualized
Jump Game 2
Greedy
Make the locally optimal choice at each step, hoping it leads to a globally optimal solution.
Like Jump Game, but instead of just checking reachability, find the minimum number of jumps needed to reach the last index. 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 II
GreedyLike Jump Game, but instead of just checking reachability, find the minimum number of jumps needed to reach the last index. The greedy strategy treats this like a level-by-level BFS: within your 'current jump's range', track the farthest you could reach with one more jump, and jump exactly when you run out of the current range.
How Jump Game 2 Works
- Track 'currentEnd' (the boundary of the current jump's range), 'farthest' (the furthest reachable with one more jump), and 'jumps' count, all starting appropriately at 0.
- Loop through the array (except the last index, since you stop once you can reach it).
- At each index, update 'farthest' to the maximum of its current value and (i + array[i]).
- When you reach 'currentEnd' (the edge of what your current number of jumps can cover), increment 'jumps' and update 'currentEnd' to 'farthest' — this represents 'using' the next jump.
- Continue until the loop finishes; 'jumps' is the minimum number needed.
Jump Game 2 Worked Example
Input: [2, 3, 1, 1, 4]
currentEnd=0,farthest=0,jumps=0. i=0: farthest=max(0,2)=2. i==currentEnd(0) → jumps=1, currentEnd=2. i=1: farthest=max(2,1+3)=4. i=2: farthest=max(4,2+1)=4. i==currentEnd(2) → jumps=2, currentEnd=4. Loop ends (last index reached). Minimum jumps = 2.
def jump_game2(a):
jumps = cur_end = cur_far = 0
for i in range(len(a) - 1):
cur_far = max(cur_far, i + a[i])
if i == cur_end:
jumps += 1
cur_end = cur_far
return jumpsBehind 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 2 Time & Space Complexity
When to Use Jump Game 2
- Minimum-hop routing problems: fewest relays/hops needed to reach a destination given per-node range.
- Game level design: minimum moves to cross a board with variable jump distances.
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.