Visualize

Pattern visualizer

Jump Game II

Think of jump decisions as BFS levels: level 0 is your starting point, level 1 contains all indices reachable in 1 jump, level 2 all reachable in 2 jumps, and so on. Instead of maintaining an explicit queue, we track two frontiers: currEnd (the boundary of the current jump level) and farthest (the furthest index reachable from ANY cell in the current level). As we scan i, we update farthest = max(farthest, i + nums[i]). Whenever i reaches currEnd, we MUST spend a jump to enter the next level, setting currEnd = farthest. This finds the minimum jumps in one linear pass. Animated on: nums = [2, 3, 1, 1, 4] — find the minimum number of jumps needed to reach index 4..

Greedy BFS-level jumps to the destination

time O(n)space O(1)step 1 / 8
2
[0]
3
[1]
1
[2]
1
[3]
4
[4]
line 2

Start at index 0 with jumps=0, currEnd=0, farthest=0. Destination is index 4.

Pseudocode
1FUNCTION jump(nums):
2 jumps = 0, currEnd = 0, farthest = 0
3 FOR i from 0 to (length of nums) - 2:
4 farthest = the larger of farthest and i + nums[i]
5 IF i equals currEnd:
6 add 1 to jumps
7 currEnd = farthest
8 RETURN jumps

← / → step · space play · Home restart

Where to practice Dynamic Programming