PracticeNeetCode ↗LeetCode ↗
Given an integer array nums where each element is the maximum jump length from that position, return the minimum number of jumps needed to reach the last index. It's guaranteed the last index is always reachable.
jumps = 0, curEnd = 0 (boundary of the current jump), farthest = 0.i from 0 to len(nums) - 2: update farthest = max(farthest, i + nums[i]).i == curEnd (the current jump's range is exhausted), increment jumps and set curEnd = farthest.jumps once the loop completes.Time: O(n) — Space: O(1)
def jump(nums: list[int]) -> int:
jumps = 0
curEnd = 0
farthest = 0
for i in range(len(nums) - 1):
farthest = max(farthest, i + nums[i])
if i == curEnd:
jumps += 1
curEnd = farthest
return jumpsHow the solution above works, piece by piece.
farthest tracks the furthest index reachable from anything in the current range.i reaches curEnd (the end of the current range), one more jump is required; the next range ends at farthest.Running it on nums = [2, 3, 1, 1, 4]:
curEnd is the end of the current level; reaching it means one more jump is needed. The answer is 2 (0 → 1 → 4).