← DSA
MEDIUM

Jump Game II

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.

Example

Input nums = [2,3,1,1,4]
Output 2

Key Pointers

Step-by-Step Analysis

  1. Initialize jumps = 0, curEnd = 0 (boundary of the current jump), farthest = 0.
  2. For each index i from 0 to len(nums) - 2: update farthest = max(farthest, i + nums[i]).
  3. If i == curEnd (the current jump's range is exhausted), increment jumps and set curEnd = farthest.
  4. Return jumps once the loop completes.

Complexity

Time: O(n) — Space: O(1)

Code

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 jumps

Code Explanation

How the solution above works, piece by piece.

  1. Treat reachable indices as levels, like BFS: all indices reachable with the same number of jumps form one range.
  2. farthest tracks the furthest index reachable from anything in the current range.
  3. When i reaches curEnd (the end of the current range), one more jump is required; the next range ends at farthest.
  4. The loop stops before the last index: being at the last index needs no further jump.
  5. O(n) time, O(1) space.

Visual Walkthrough

Running it on nums = [2, 3, 1, 1, 4]:

Ranges reachable with 0, 1 and 2 jumpsBFS-style ranges:231140 jumps1 jump2 jumpstrace2031121344i=0farthest 2 → jump #1, range now ends at 223114i=1farthest 423114i=2farthest 4 → jump #2, range now ends at 423114i=3farthest 4
Think of it as BFS by levels: index 0 is level 0; indices 1–2 are reachable with 1 jump; from those, indices 3–4 with 2 jumps. curEnd is the end of the current level; reaching it means one more jump is needed. The answer is 2 (0 → 1 → 4).
start / current1 jump2 jumps

Video Explanation

NeetCode — Greedy, LeetCode 45