15% off all plans & roadmaps Use code
See plansJump Game II
- LeetCode 45
- Medium
- Greedy Patterns
- Jump Game Reachability/Minimization
Updated
TL;DR: Find the fewest jumps needed to get from index 0 to the last index, where each value is the maximum forward jump. Treat the array as layers of reachable indices and count how many layers you cross, which a single greedy pass does in O(n).
Problem
You are given a 0-indexed array of integers nums of length n. You start at index 0.
Each value nums[i] is the maximum length of a forward jump from index i. From index i you may jump to any index i + j where:
0 <= j <= nums[i], andi + j < n.
Return the minimum number of jumps needed to reach index n - 1. The test cases guarantee that the last index is reachable.
Example 1
Input: nums = [2,3,1,1,4] Output: 2 Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to index 1, then 3 steps to the last index.
Example 2
Input: nums = [2,3,0,1,4] Output: 2
Constraints
1 <= nums.length <= 10^40 <= nums[i] <= 1000- It is guaranteed that you can reach
nums[n - 1].
Constraints that matter
- n up to 10^4 rules out exponential recursion without memoization. Plain recursion tries every jump sequence, and the number of sequences grows exponentially.
- n up to 10^4 and nums[i] up to 1000 bound the DP baseline at about n * 1000 = 10^7 steps, which passes. Without the cap on values it would be O(n^2) = 10^8 in the worst case.
- The last index is always reachable, so you never need a fallback for an impossible case. You also do not need to detect a stuck window.
- nums[i] can be 0, so a position may be a dead end. The greedy window handles this because it only cares about the best reach inside the window.
- n can be 1, so the answer is 0 and the loop must not read past the array.
Hints
Hint 1
This is a greedy problem that behaves like a breadth-first search on an implicit graph.
Hint 2
The most direct idea is to try every jump.
Solution
Intuition
This is a greedy problem that behaves like a breadth-first search on an implicit graph. Each index is a node, and index i has edges to every index from i + 1 to i + nums[i]. The answer is the shortest path length from index 0 to index n - 1, and every edge costs one jump.
Picture a bus route where you ride as far as the current bus allows, noting the farthest stop any rider could reach. The variable end is the current bus's last stop, and jumps counts how many bus changes you make.
Breadth-first search visits nodes level by level. Level 0 is index 0. Level 1 is every index reachable in one jump. Level 2 is every index reachable in two jumps but not one.
Each level here is a contiguous block of indices, because a jump can land on any index up to its maximum. So you never need a queue. You only need the right edge of the current level and the right edge of the next level.
While you scan the current level, you track the farthest index any of its members can reach. That value is the right edge of the next level. When the scan passes the end of the current level, you must take one more jump, and the next level becomes the current one.
Greedy is safe because every index in a level costs the same number of jumps, so landing farther is never worse than landing nearer. You do not have to pick which index to land on. You only record the best reach, and the count of levels crossed is the minimum number of jumps.
Worked example
Input: nums = [6, 2, 4, 0, 5, 1, 1, 4, 2, 9] Output: 2 Explanation: Jump from index 0 to index 4 (a jump of 4 is allowed because nums[0] is 6). From index 4, nums[4] is 5, so you can land on index 9, the last index. Two jumps is the minimum because one jump from index 0 reaches at most index 6.
Approach 1: Dynamic programming over every reachable index
The most direct idea is to try every jump. Plain recursion defines f(i) = 1 + min(f(i + step)) for every step from 1 to nums[i]. It recomputes the same suffix from many starting points, so it takes exponential time and fails at n = 10^4. Caching f fixes the repeats, and the bottom-up form of that cache is the DP below.
Keep dp[j], the fewest jumps found so far to reach index j. Start with dp[0] = 0 and everything else at a large value. Walk the indices left to right. From index i, try every landing spot j from i + 1 to i + nums[i] and relax dp[j] = min(dp[j], dp[i] + 1).
By the time you stand on i, every earlier index that could reach i has already pushed its value into dp[i], so dp[i] is final. The answer is dp[n - 1].
Steps
- Let
n = len(nums). Createdpof sizenfilled with a large value such asn + 1, and setdp[0] = 0. - Loop
ifrom 0 ton - 2. - Compute
reach = min(n - 1, i + nums[i])so you never write past the array. - Loop
jfromi + 1toreach. - If
dp[i] + 1 < dp[j], setdp[j] = dp[i] + 1. - Return
dp[n - 1].
Dry run
Example: [6, 2, 4, 0, 5, 1, 1, 4, 2, 9], so n = 10. Start with dp = [0, X, X, X, X, X, X, X, X, X] where X is the large value.
i = 0, reach 6: indices 1 to 6 all get 1. Nowdp = [0,1,1,1,1,1,1,X,X,X].i = 1, reach 3: candidates are 2, so no change on indices 2 and 3 (1 is already smaller).i = 2, reach 6: candidates are 2, no change.i = 3,nums[3] = 0: nothing to relax.i = 4, reach 9: indices 5 and 6 stay at 1. Indices 7, 8 and 9 get 2. Nowdp = [0,1,1,1,1,1,1,2,2,2].i = 5toi = 8: every relaxation offers 2 or more to indices that already hold 2 or less, so nothing changes.
dp[9] = 2, which matches the expected output.
Complexity
| Time | O(n * k), at most O(n^2) |
|---|---|
| Space | O(n) |
Here n is the array length and k is the largest value in nums. The outer loop runs n - 1 times and the inner loop runs at most nums[i] times, so the total is at most n * k relaxations. With the stated limits that is about 10^7, and in general it is O(n^2) when values can be as large as n. The dp array holds n integers, so space is O(n).
PythonTested in our runner
from typing import List, Optional
class Solution:
def jump(self, nums: List[int]) -> int:
n = len(nums)
dp = [n + 1] * n
dp[0] = 0
for i in range(n - 1):
reach = min(n - 1, i + nums[i])
nxt = dp[i] + 1
for j in range(i + 1, reach + 1):
if nxt < dp[j]:
dp[j] = nxt
return dp[n - 1]
JavaTested in our runner
import java.util.*;
class Solution {
public int jump(int[] nums) {
int n = nums.length;
int[] dp = new int[n];
Arrays.fill(dp, n + 1);
dp[0] = 0;
for (int i = 0; i < n - 1; i++) {
int reach = Math.min(n - 1, i + nums[i]);
for (int j = i + 1; j <= reach; j++) {
if (dp[i] + 1 < dp[j]) {
dp[j] = dp[i] + 1;
}
}
}
return dp[n - 1];
}
}
C++Tested in our runner
using namespace std;
class Solution {
public:
int jump(vector<int>& nums) {
int n = nums.size();
vector<int> dp(n, n + 1);
dp[0] = 0;
for (int i = 0; i < n - 1; i++) {
int reach = min(n - 1, i + nums[i]);
for (int j = i + 1; j <= reach; j++) {
if (dp[i] + 1 < dp[j]) {
dp[j] = dp[i] + 1;
}
}
}
return dp[n - 1];
}
};
JavaScriptTested in our runner
/**
* @param {number[]} nums
* @return {number}
*/
var jump = function(nums) {
const n = nums.length;
const dp = new Array(n).fill(n + 1);
dp[0] = 0;
for (let i = 0; i < n - 1; i++) {
const reach = Math.min(n - 1, i + nums[i]);
for (let j = i + 1; j <= reach; j++) {
if (dp[i] + 1 < dp[j]) {
dp[j] = dp[i] + 1;
}
}
}
return dp[n - 1];
};
GoTested in our runner
func jump(nums []int) int {
n := len(nums)
dp := make([]int, n)
for i := range dp {
dp[i] = n + 1
}
dp[0] = 0
for i := 0; i < n-1; i++ {
reach := i + nums[i]
if reach > n-1 {
reach = n - 1
}
for j := i + 1; j <= reach; j++ {
if dp[i]+1 < dp[j] {
dp[j] = dp[i] + 1
}
}
}
return dp[n-1]
}
C#Tested in our runner
public class Solution {
public int jump(int[] nums) {
int n = nums.Length;
int[] dp = new int[n];
Array.Fill(dp, n + 1);
dp[0] = 0;
for (int i = 0; i < n - 1; i++) {
int reach = Math.Min(n - 1, i + nums[i]);
for (int j = i + 1; j <= reach; j++) {
if (dp[i] + 1 < dp[j]) {
dp[j] = dp[i] + 1;
}
}
}
return dp[n - 1];
}
}

Solution pattern
Jump Game Reachability/Minimization
Part of Greedy Patterns
Approach 2: Greedy window (implicit BFS)OptimalJump Game Reachability/Minimization
What's slow: the DP writes to every index in every reach range, even though most of those writes change nothing. In the trace above, only the first visit to each index mattered. Every index in a level has the same jump count, so storing per-index counts is wasted work.
The insight that fixes it: the indices reachable with k jumps form a contiguous block. You do not need to know which index inside the block to land on. You only need the farthest index that any member of the block can reach, because that sets the right edge of the next block.
Keep three numbers. jumps counts the levels crossed. end is the right edge of the current level. farthest is the best i + nums[i] seen so far. Scan left to right and update farthest at each index. When i reaches end, you have seen the whole level, so take a jump and set end = farthest.
Steps
- Set
jumps = 0,end = 0,farthest = 0. - Loop
ifrom 0 ton - 2. Stop before the last index because you never jump from it. - Update
farthest = max(farthest, i + nums[i]). - If
i == end, you have scanned the whole current level, so incrementjumps. - Set
end = farthestto define the next level. - After the loop, return
jumps. For n = 1 the loop does not run and the answer is 0.
Dry run
Example: [6, 2, 4, 0, 5, 1, 1, 4, 2, 9], n = 10, so i runs from 0 to 8. Each row shows the state after processing index i.
| i | nums[i] | i + nums[i] | farthest | i == end? | jumps | end |
|---|---|---|---|---|---|---|
| start | 0 | 0 | 0 | |||
| 0 | 6 | 6 | 6 | yes (0 == 0) | 1 | 6 |
| 1 | 2 | 3 | 6 | no | 1 | 6 |
| 2 | 4 | 6 | 6 | no | 1 | 6 |
| 3 | 0 | 3 | 6 | no | 1 | 6 |
| 4 | 5 | 9 | 9 | no | 1 | 6 |
| 5 | 1 | 6 | 9 | no | 1 | 6 |
| 6 | 1 | 7 | 9 | yes (6 == 6) | 2 | 9 |
| 7 | 4 | 11 | 11 | no | 2 | 9 |
| 8 | 2 | 10 | 11 | no | 2 | 9 |
The loop ends after index 8 and end = 9 already covers the last index. The function returns jumps = 2, which matches the expected output. Index 4 set the key reach of 9, even though index 0 had the largest value.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Here n is the array length. The loop visits each index from 0 to n - 2 exactly once, and each visit does a constant amount of work: one addition, one max, one comparison. That gives O(n) time. The algorithm stores only three integers, so space is O(1) no matter how large the input is.
PythonTested in our runner
from typing import List, Optional
class Solution:
def jump(self, nums: List[int]) -> int:
jumps = 0
end = 0 # right edge of the current level
farthest = 0 # best reach from any index scanned so far
for i in range(len(nums) - 1):
farthest = max(farthest, i + nums[i])
if i == end:
jumps += 1
end = farthest
return jumps
JavaTested in our runner
import java.util.*;
class Solution {
public int jump(int[] nums) {
int jumps = 0;
int end = 0; // right edge of the current level
int farthest = 0; // best reach from any index scanned so far
for (int i = 0; i < nums.length - 1; i++) {
farthest = Math.max(farthest, i + nums[i]);
if (i == end) {
jumps++;
end = farthest;
}
}
return jumps;
}
}
C++Tested in our runner
using namespace std;
class Solution {
public:
int jump(vector<int>& nums) {
int jumps = 0;
int end = 0; // right edge of the current level
int farthest = 0; // best reach from any index scanned so far
for (int i = 0; i < (int)nums.size() - 1; i++) {
farthest = max(farthest, i + nums[i]);
if (i == end) {
jumps++;
end = farthest;
}
}
return jumps;
}
};
JavaScriptTested in our runner
/**
* @param {number[]} nums
* @return {number}
*/
var jump = function(nums) {
let jumps = 0;
let end = 0; // right edge of the current level
let farthest = 0; // best reach from any index scanned so far
for (let i = 0; i < nums.length - 1; i++) {
farthest = Math.max(farthest, i + nums[i]);
if (i === end) {
jumps++;
end = farthest;
}
}
return jumps;
};
GoTested in our runner
func jump(nums []int) int {
jumps := 0
end := 0 // right edge of the current level
farthest := 0 // best reach from any index scanned so far
for i := 0; i < len(nums)-1; i++ {
if i+nums[i] > farthest {
farthest = i + nums[i]
}
if i == end {
jumps++
end = farthest
}
}
return jumps
}
C#Tested in our runner
public class Solution {
public int jump(int[] nums) {
int jumps = 0;
int end = 0; // right edge of the current level
int farthest = 0; // best reach from any index scanned so far
for (int i = 0; i < nums.Length - 1; i++) {
farthest = Math.Max(farthest, i + nums[i]);
if (i == end) {
jumps++;
end = farthest;
}
}
return jumps;
}
}
Common mistakes
- Looping to
i < ninstead ofi < n - 1. Ifendequals the last index, the loop reaches it and adds one extra jump from a position you never need to leave. Stop atn - 2. - Updating
endbeforefarthest, or moving theif i == endcheck above thefarthest = max(...)line. Then indexenditself is left out of the next level's reach. Updatefarthestfirst, then test the boundary. - Greedily jumping to the index with the largest
nums[i]instead of the largesti + nums[i]. A smaller value further right can reach more. Track the reach, not the value. - Resetting
farthest = 0when you take a jump. The reach from earlier indices still counts toward the next level, so keepfarthestrunning. Onlyendchanges at a boundary. - Writing
jumps = 1as the start value. Fornums = [0]or[5]the answer is 0, and the loop never runs. Start at 0 and let the boundary check add jumps. - In the DP, running
jup toi + nums[i]with no cap. The loop writes past indexn - 1and crashes in Java, C++ and C#. Cap it withmin(n - 1, i + nums[i]).
Edge cases
nums = [0]: you are already at the last index, so the answer is 0.nums = [1, 1, 1, 1]: every jump is forced, so the answer is 3 (n - 1).nums = [10, 1, 1, 1]: the first value covers the whole array, so the answer is 1.nums = [2, 3, 0, 1, 4]: a zero in the middle does not matter because index 1 reaches the last index. The answer is 2.nums = [1, 2]: a short array where the first jump already ends at the last index. The answer is 1.- Maximum size, n = 10^4 with all values 1: the greedy loop does 10^4 steps and returns 9999. The DP stays fast because each inner loop has length 1.
Follow-ups interviewers ask
- What if the array could contain values that make the last index unreachable?
- Add a stuck check. If
i > farthestat any point, the next index cannot be reached, so return -1. This is the same reachability test as Jump Game I. In the window version, you can also check thatfarthest > iwheneveri == end, because otherwise the next level would be empty. - Can you also return the actual path of indices?
- Yes. In the DP, store a parent index each time you improve
dp[j], then walk back fromn - 1. In the greedy version, record the index that producedfarthestat each boundary. Those indices form a valid shortest path, because the best-reaching index of each level is a legal landing spot from the previous level. - Why does the greedy scan not need a queue like a normal BFS?
- Each level is a contiguous range, since a jump can land anywhere from i + 1 to i + nums[i]. A contiguous range is fully described by its right edge, so
endreplaces the queue. The next level starts right afterendand stops atfarthest, which is why one pass with three integers is enough.
Jump Game II FAQ
What is the time complexity of Jump Game II?
The greedy solution runs in O(n) time and O(1) space, where n is the length of nums. It visits each index once. The DP baseline is O(n * k), at most O(n^2), where k is the largest jump value.
Why use a greedy window for Jump Game II?
All indices in one level cost the same number of jumps, and each level is a contiguous block. Only the farthest reach of the block matters for the next level. That lets you replace a per-index table with two boundaries and finish in one pass.
Can Jump Game II be solved in O(1) extra space?
Yes. The greedy version keeps only jumps, end and farthest. The DP needs an array of size n, and the recursive version needs a call stack up to depth n, so those use O(n) space.
How is Jump Game II different from Jump Game (LeetCode 55)?
Jump Game asks whether the last index is reachable, so a single running farthest is enough. Jump Game II asks for the minimum number of jumps and guarantees reachability. You keep the same farthest but add the end boundary to count levels.
Why does the loop stop at n - 2 in Jump Game II?
Once you stand on the last index, the task is finished and you do not jump again. If the loop includes index n - 1 and end equals n - 1, the boundary check adds a jump that is not needed. Stopping at n - 2 avoids that off-by-one.
Why does the recursive brute force fail on Jump Game II?
The recursion explores every jump sequence and recomputes the same suffix from many starting points, so its running time grows exponentially in n. Memoization cuts it to O(n^2) at worst, but the greedy window solution reaches O(n).
Asked at
See which companies ask this — Pro
Related problems
- Jump Game · same technique: Jump Game Reachability/Minimization
- Candy · next harder, same pattern
- Merge Intervals · same pattern: Greedy Patterns
- Gas Station · same pattern: Greedy Patterns
- Task Scheduler · same pattern: Greedy Patterns
- Non-overlapping Intervals · same pattern: Greedy Patterns
- Insert Interval · same pattern: Greedy Patterns
- Partition Labels · same pattern: Greedy Patterns
- Hand of Straights · same pattern: Greedy Patterns
- Merge Triplets to Form Target Triplet · same pattern: Greedy Patterns