Problem
Same setup as Jump Game — each element is the farthest you can jump forward from that position, and the last index is always reachable. Find the minimum number of jumps needed to get there.
Signal
"Minimum number of jumps" on top of a reachability array is a level-by-level expansion — the same shape as BFS on an implicit graph, but collapsible into a single greedy pass since only the farthest reach per level matters.
Approach
Think of each jump as covering a "level": everything reachable within the
current jump count. Track two things while scanning left to right — the
boundary of the current jump (current_end), and the farthest index reachable
using one more jump (farthest). When the scan reaches current_end, that
level is exhausted: increment the jump count and advance current_end to
farthest.
Skeleton
jumps = current_end = farthest = 0
for i in range(len(nums) - 1):
farthest = max(farthest, i + nums[i])
if i == current_end:
jumps += 1
current_end = farthest
return jumps
Solution
def jump(nums: list[int]) -> int:
jumps = current_end = farthest = 0
for i in range(len(nums) - 1):
farthest = max(farthest, i + nums[i])
if i == current_end:
jumps += 1
current_end = farthest
return jumps
Complexity
O(n) time — one pass. O(1) space.
Pitfalls
- The loop bound is
len(nums) - 1, notlen(nums)— you never need to "jump" from the last index itself, and including it can over-count by triggering one extra boundary increment. - Incrementing
jumpsbased on array index boundaries (current_end) rather than actual BFS queue levels is the whole trick — reproducing this with an actual BFS over positions works but is needless overhead. - Confusing this with Jump Game (reachability only) is easy since the setup
looks identical — the tell is "minimum number of jumps," which needs the
extra
current_end/jumpsbookkeeping this problem adds.