Skip to content
Problem 45 · LeetCode 45(opens in a new tab)

Jump Game II

MediumArrays

You are given nums, an array of whole numbers, and you stand on index 0. From index i you may jump forward by any distance from 1 up to nums[i], as long as you stay inside the array.

Return the smallest number of jumps that gets you to the last index. The input always allows you to get there.

Example 1

Input:  nums = [2, 1, 3, 1, 1, 2]
Output: 2
Why:    0 → 2 (value 3), then 2 → 5
2 more examples and the constraints

Example 2

Input:  nums = [1, 1, 1]
Output: 2
Why:    every jump moves one step

Example 3

Input:  nums = [5]
Output: 0
Why:    you already stand on the last index

Constraints

  • 1 ≤ length of nums ≤ 10,000
  • 0 ≤ nums[i] ≤ 1,000
  • The last index can always be reached

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Fewest jumps to every index (DP)O(n · m)
  2. Greedy reach, one passO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 indexes, jumps up to 1,000Verdict
Fewest jumps to every index (DP)O(n · m)
Passes, but does extra work
Greedy reach, one passO(n)
Best; one pass, three counters

n = length of nums, m = the largest jump length.

Edge cases to test

  • One element. [5] needs 0 jumps; the loop body never runs.
  • Zeros on the way. [2, 0, 0] still takes 1 jump: index 0 reaches the end directly.
  • A jump that overshoots. [10, 0, 0] is one jump; reaching past the end is fine.
  • All ones. Every jump is forced, so the answer is n − 1.

Common mistakes

  • Looping over the last index too, which counts one extra jump when i lands on end there.
  • Always jumping as far as possible, which can land on a 0 or a short jump and miss a better route.
  • Counting a jump every time far grows instead of only when the current block is used up.

How to talk through it

  1. 1Clarify. Is the end always reachable? May a jump go past the last index?
  2. 2Give the DP. Fewest jumps to each index, filled left to right; say it is O(n · m).
  3. 3See the layers. Indexes reachable in j jumps form one block, like a BFS level.
  4. 4Code the greedy. Track end and far; a jump happens only when i reaches end.
  5. 5Test out loud. Run the one-element case and an all-ones array before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?