15% off all plans & roadmaps Use code

See plans

Jump Game II

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], and
  • i + 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^4
  • 0 <= 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.

View on LeetCode

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.

Watch the pattern animation

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

  1. Let n = len(nums). Create dp of size n filled with a large value such as n + 1, and set dp[0] = 0.
  2. Loop i from 0 to n - 2.
  3. Compute reach = min(n - 1, i + nums[i]) so you never write past the array.
  4. Loop j from i + 1 to reach.
  5. If dp[i] + 1 < dp[j], set dp[j] = dp[i] + 1.
  6. 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. Now dp = [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. Now dp = [0,1,1,1,1,1,1,2,2,2].
  • i = 5 to i = 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

TimeO(n * k), at most O(n^2)
SpaceO(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]
Jump Game Reachability/Minimization pattern infographic for Jump Game II

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

  1. Set jumps = 0, end = 0, farthest = 0.
  2. Loop i from 0 to n - 2. Stop before the last index because you never jump from it.
  3. Update farthest = max(farthest, i + nums[i]).
  4. If i == end, you have scanned the whole current level, so increment jumps.
  5. Set end = farthest to define the next level.
  6. 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.

inums[i]i + nums[i]farthesti == end?jumpsend
start000
0666yes (0 == 0)16
1236no16
2466no16
3036no16
4599no16
5169no16
6179yes (6 == 6)29
741111no29
821011no29

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

TimeO(n)
SpaceO(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

Common mistakes

  • Looping to i < n instead of i < n - 1. If end equals the last index, the loop reaches it and adds one extra jump from a position you never need to leave. Stop at n - 2.
  • Updating end before farthest, or moving the if i == end check above the farthest = max(...) line. Then index end itself is left out of the next level's reach. Update farthest first, then test the boundary.
  • Greedily jumping to the index with the largest nums[i] instead of the largest i + nums[i]. A smaller value further right can reach more. Track the reach, not the value.
  • Resetting farthest = 0 when you take a jump. The reach from earlier indices still counts toward the next level, so keep farthest running. Only end changes at a boundary.
  • Writing jumps = 1 as the start value. For nums = [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 j up to i + nums[i] with no cap. The loop writes past index n - 1 and crashes in Java, C++ and C#. Cap it with min(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 > farthest at 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 that farthest > i whenever i == 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 from n - 1. In the greedy version, record the index that produced farthest at 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 end replaces the queue. The next level starts right after end and stops at farthest, 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

Practise it