150NeetCode 150

124.Jump Game II

MediumGreedy Ā· 3/8

Problem

You are given an integer array nums and start at index 0. 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 the last index. The test cases guarantee that the last index is reachable.

Examples

Input:  nums = [2,3,1,1,4]
Output: 2
Explanation: Jump 0 -> 1 (1 step), then 1 -> 4 (3 steps).
Input:  nums = [2,3,0,1,4]
Output: 2
Explanation: Again 0 -> 1 -> 4.
Input:  nums = [0]
Output: 0
Explanation: Already at the last index.

Constraints

  • 1 <= nums.length <= 10^4
  • 0 <= nums[i] <= 1000
  • It is guaranteed that you can reach nums[n - 1].

šŸ’” Key Insight

Think of it as BFS over indices, where "level k" is the set of indices reachable with exactly k jumps. Because reachable sets are contiguous, every level is just a window [l, r]. The next window runs from r + 1 to the farthest i + nums[i] for any i in the current window. Counting windows until one covers n - 1 gives the answer in a single O(n) pass with O(1) memory.

Brute Force Recursion

TimeO(k^n) worst caseSpaceO(n)

Intuition

From index i, try every jump 1..nums[i] and take 1 + the best result from the landing spot. Without caching, the same suffix is solved again and again.

Algorithm

  1. minJumps(i): if i >= n - 1 return 0.
  2. best = INF; for each step in 1..nums[i]: best = min(best, 1 + minJumps(i + step)).
  3. Return best.

Visualization

nums = [2,3,1,1,4]
minJumps(0) = 1 + min(minJumps(1), minJumps(2))
minJumps(1) = 1 + min(minJumps(2), minJumps(3), minJumps(4)=0) = 1
minJumps(2) = 1 + minJumps(3) = 1 + 1 = 2
minJumps(0) = 1 + min(1, 2) = 2

Code

java
class Solution {
    public int jump(int[] nums) {
        return minJumps(nums, 0);
    }

    private int minJumps(int[] nums, int i) {
        if (i >= nums.length - 1) {
            return 0;
        }
        int best = Integer.MAX_VALUE;
        for (int step = 1; step <= nums[i]; step++) {
            int sub = minJumps(nums, i + step);
            if (sub != Integer.MAX_VALUE) {
                best = Math.min(best, 1 + sub); // guard against dead ends
            }
        }
        return best;
    }
}

Complexity

  • Time: O(k^n) worst case — k is the maximum jump length; overlapping subproblems explode.
  • Space: O(n) — recursion depth.

Complexity Comparison

Approach Time Space
Brute Force Recursion O(k^n) O(n)
Bottom-Up DP O(n Ā· k) O(n)
Greedy BFS Windows O(n) O(1)

Common Pitfalls

  • Looping to n - 1 inclusive in the greedy version — if currentEnd lands exactly on the last index, you would count an extra jump.
  • Greedily jumping to the index with the largest nums[i] value instead of the index that reaches farthest (i + nums[i]).
  • Adding 1 + INF in DP, which overflows to a negative number; guard unreachable entries.
  • Forgetting the n = 1 case, which must return 0.