The Runtime Theory
mediumleetcode#greedy

Jump Game

Decide if you can reach the last index when each element is the maximum jump length; a greedy reach tracker only moves forward.

The Runtime Theory Team1 min read
Solve it

solving happens on the judge — come back and mark it done

Sample cases

innums = [2,3,1,1,4]

outtrue

innums = [3,2,1,0,4]

outfalse

Given an array where each element is the maximum number of steps the machine may jump forward from that index, it must decide whether the last index is reachable. The jump can be any length from 1 up to the element's value, and the machine may stop at any intermediate index along the way.

The key insight is that the machine never needs to decide which jump to take — it only needs to know how far it could have gotten. If the farthest reachable index from all positions visited so far ever falls behind the current position, the machine is stuck and the answer is false.

The approach runs in three steps. First, initialize a reach tracker to 0. Second, walk the array from left to right: if the current index is beyond reach, return false; otherwise extend reach with the maximum of its current value and index plus the jump length at this position. Third, if the walk completes, return true. Time is O(n) and space is O(1).

The trickiest edge case is a single-element array, where the machine is already at the last index and must return true even if the element is 0. The reach-based loop handles it because index 0 is never beyond reach 0. The classic false case is [3,2,1,0,4], where every reachable path funnels into a zero and stalls.

python
def canJump(nums):
    reach = 0
    for i, n in enumerate(nums):
        if i > reach:
            return False
        reach = max(reach, i + n)
    return True

More practice in this topic

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.