Full answer
Problem
Given nums where nums[i] is the maximum jump length from index i, start at index 0.
- Part 1: return whether the last index is reachable.
- Part 2: assuming it is reachable, return the minimum number of jumps.
Example: [2, 3, 1, 1, 4] is reachable in 2 jumps (0 to 1, then 1 to 4). [3, 2, 1, 0, 4] is not reachable, because every path lands on the 0 at index 3.
Constraints: 1 <= n <= 10^4, values from 0 to 1,000.
Brute force
BFS or DP over indices: from each index, try every jump length. dp[j] = min(dp[i] + 1) for all i that can reach j. That is O(n^2) in the worst case (up to O(n * max jump)).
Optimal approach
Reachability: far = 0; for each i, if i > far return False; else far = max(far, i + nums[i]). Return True.
Minimum jumps: keep end (last index reachable with the current number of jumps) and far (farthest reachable with one more jump). For i from 0 to n - 2: update far; when i == end, increment jumps and set end = far.
Why it works
Reachability: the set of reachable indices is always a prefix [0, far], because from any reachable index every shorter jump is also allowed. If index i is beyond far, nothing reachable can jump to it, and nothing beyond it is reachable either.
Minimum jumps: indices reachable with exactly j jumps form a contiguous block, and the next block ends at the farthest point reachable from the current block. Counting how many blocks are needed to cover the last index is exactly BFS by layers, done without a queue because each layer is a range.
Complexity
O(n) time and O(1) space for both parts.
Code
import random
from collections import deque
def can_reach_end(nums):
"""nums[i] is the maximum jump from i. Track the farthest reachable index. O(n), O(1)."""
far = 0
for i, x in enumerate(nums):
if i > far:
return False # stuck: i cannot be reached
far = max(far, i + x)
return True
def min_jumps(nums):
"""Fewest jumps to the last index (assumed reachable). Greedy BFS by layers: O(n)."""
jumps, end, far = 0, 0, 0
for i in range(len(nums) - 1):
far = max(far, i + nums[i])
if i == end: # finished the current layer: one more jump
jumps += 1
end = far
return jumps
def brute_min(nums):
"""Plain BFS over indices, O(n^2) worst case. -1 when unreachable."""
n = len(nums)
dist = [-1] * n
dist[0] = 0
q = deque([0])
while q:
i = q.popleft()
for j in range(i + 1, min(n, i + nums[i] + 1)):
if dist[j] == -1:
dist[j] = dist[i] + 1
q.append(j)
return dist[-1]
if __name__ == "__main__":
assert can_reach_end([2, 3, 1, 1, 4]) and not can_reach_end([3, 2, 1, 0, 4])
assert can_reach_end([0]) # already at the end
assert min_jumps([2, 3, 1, 1, 4]) == 2 and min_jumps([2, 3, 0, 1, 4]) == 2 and min_jumps([0]) == 0
rng = random.Random(92)
for _ in range(2000):
a = [rng.randint(0, 4) for _ in range(rng.randint(1, 12))]
b = brute_min(a)
assert can_reach_end(a) == (b != -1)
if b != -1:
assert min_jumps(a) == b
print("all tests passed")Save as b92_jump_game.py and run python3 b92_jump_game.py. It prints all tests passed (Python 3.13.5).
Edge cases
Single element (reachable, 0 jumps). Zeros that can be jumped over. A zero at index 0 with n > 1 (unreachable). The loop for minimum jumps stops at n - 2 so that reaching the last index does not count an extra jump.
Pattern
Greedy over a reachable frontier, equivalent to BFS layers on an interval graph. Related: jump game with exact jumps in both directions (BFS), minimum taps to water a garden and video stitching (same layer greedy after converting to intervals), and frog jumps with costs (DP).
import random
from collections import deque
def can_reach_end(nums):
"""nums[i] is the maximum jump from i. Track the farthest reachable index. O(n), O(1)."""
far = 0
for i, x in enumerate(nums):
if i > far:
return False # stuck: i cannot be reached
far = max(far, i + x)
return True
def min_jumps(nums):
"""Fewest jumps to the last index (assumed reachable). Greedy BFS by layers: O(n)."""
jumps, end, far = 0, 0, 0
for i in range(len(nums) - 1):
far = max(far, i + nums[i])
if i == end: # finished the current layer: one more jump
jumps += 1
end = far
return jumps
def brute_min(nums):
"""Plain BFS over indices, O(n^2) worst case. -1 when unreachable."""
n = len(nums)
dist = [-1] * n
dist[0] = 0
q = deque([0])
while q:
i = q.popleft()
for j in range(i + 1, min(n, i + nums[i] + 1)):
if dist[j] == -1:
dist[j] = dist[i] + 1
q.append(j)
return dist[-1]
if __name__ == "__main__":
assert can_reach_end([2, 3, 1, 1, 4]) and not can_reach_end([3, 2, 1, 0, 4])
assert can_reach_end([0]) # already at the end
assert min_jumps([2, 3, 1, 1, 4]) == 2 and min_jumps([2, 3, 0, 1, 4]) == 2 and min_jumps([0]) == 0
rng = random.Random(92)
for _ in range(2000):
a = [rng.randint(0, 4) for _ in range(rng.randint(1, 12))]
b = brute_min(a)
assert can_reach_end(a) == (b != -1)
if b != -1:
assert min_jumps(a) == b
print("all tests passed")Farthest-reach check and layer-counting jumps, cross-checked against BFS over indices on random arrays.
Complexity
Time: O(n). Space: O(1). The BFS reference is O(n * max jump).
By level
Fresher: Tracks the farthest reachable index and explains why falling behind it means failure. Traces both examples.
Mid: Writes the layer-based minimum jumps loop, explains the BFS equivalence, and handles the n - 2 boundary. Reconstructs the jump positions.
Senior: Maps covering problems (taps, video clips) to the same greedy and proves the contiguous-layer property. Discusses when greedy layer counting fails and BFS or DP is needed.
Key points
- Reachable indices form a prefix [0, far]
- Stuck when i > far
- Indices reachable in j jumps form a range
- Count a jump when the current range ends
- Loop to n - 2 for the jump count
Common mistakes
- Counting a jump on every index
- Looping to n - 1 and adding an extra jump
- Using DP O(n^2) when O(n) is expected
- Missing the stuck check
Follow-ups
- How would you return the actual jump positions?
- What if jumps can go left or right by exactly nums[i]?
- How does minimum taps to water a garden reduce to this?
Tips
- Explain the prefix argument for reachability
- Present the layers as implicit BFS
- Test [0] and [1, 0, 1]
Evaluation rubric
- Correct reachability
- Correct minimum jumps
- O(n)
- Explains the layer idea