Can you hop from the first index to the last? Walk once, keeping the farthest spot you can reach; if you ever stand past it, you're stuck.
▼The problem
You start at index 0 of an array of non-negative integers. Each number is the longest jump you can make from that spot (any hop from 1 up to it). Return whether you can reach the last index.
Examples (both animated):
TRY IT ON LEETCODE ▶The solution
def can_jump(nums):
farthest = 0
for i, jump in enumerate(nums):
if i > farthest:
return False # stuck
farthest = max(farthest, i + jump)
if farthest >= len(nums) - 1:
return True # covers the end
return TrueTranscript
Jump Game. You start on the first spot of a row of numbers. Each number is the farthest you can jump from that spot, so any hop from one up to that number. Can you reach the last spot?
Take two, three, one, one, four. From the two, hop one step to the three. From the three, jump three to the end. True. Now take three, two, one, zero, four. Every jump you can make lands at or before the zero, and zero goes nowhere. False.
The simple way tries every jump from every spot. Here that's four different paths, and every one dies on the zero. Each extra spot can double the paths, so it's exponential. Remembering which spots work helps, but it's still n squared.
The greedy trick: stop choosing jumps. Just track the farthest spot you can reach. Since you can always jump shorter, every spot inside the reach is reachable too. Walk left to right. At each spot, stretch the reach to i plus the jump, if that's farther. If you ever step past the reach, you're stuck.
In code, farthest starts at zero. For each index, if i is past farthest, return false. Otherwise stretch farthest to i plus the jump. Once it covers the last index, return true.
First example. At index zero, zero plus two: the reach is two. At index one, one plus three is four, the last index. True, after only two spots.
Now the trap. Index zero reaches three. Index one: one plus two, still three. Index two: two plus one, still three. Index three is the zero: three plus zero, still three. Index four is past the reach. Stuck. False.
Each spot is visited once, so the time is O of n. And the only thing to remember is the reach: constant space.
Don't plan the jumps. Just stretch the reach. That's Jump Game.