150NeetCode 150

123.Jump Game

MediumBlind 75Greedy Ā· 2/8

Problem

You are given an integer array nums. You start at index 0, and nums[i] is the maximum jump length from index i (you may jump any distance from 0 to nums[i]).

Return true if you can reach the last index, otherwise false.

Examples

Input:  nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step to index 1, then 3 steps to the last index.
Input:  nums = [3,2,1,0,4]
Output: false
Explanation: Every path lands on index 3, whose jump length is 0, so index 4 is unreachable.
Input:  nums = [0]
Output: true
Explanation: We already stand on the last index.

Constraints

  • 1 <= nums.length <= 10^4
  • 0 <= nums[i] <= 10^5

šŸ’” Key Insight

The set of reachable indices is always a contiguous prefix [0, farthest]: if you can reach index i, you can reach every index before it too. So we only need to track farthest, the furthest index reachable so far. Walking left to right, if we ever stand on an index beyond farthest, we are stuck; otherwise extend farthest with i + nums[i].

Brute Force Recursion

TimeO(2^n) in the worst caseSpaceO(n)

Intuition

From index i, try every jump length 1..nums[i] and recursively ask whether the landing index can reach the end. This explores every path and is exponential because the same index is re-solved many times.

Algorithm

  1. canReach(i): if i >= n - 1 return true.
  2. For step from nums[i] down to 1: if canReach(i + step) return true.
  3. Return false.

Visualization

nums = [3,2,1,0,4]
canReach(0) -> try 3: canReach(3) stuck (nums[3] = 0)
            -> try 2: canReach(2) -> canReach(3) stuck again
            -> try 1: canReach(1) -> canReach(3), canReach(2) -> ... all stuck
index 3 is solved many times -> exponential blow-up

Code

java
class Solution {
    public boolean canJump(int[] nums) {
        return canReach(nums, 0);
    }

    private boolean canReach(int[] nums, int i) {
        if (i >= nums.length - 1) {
            return true;
        }
        // try longer jumps first; any success is enough
        for (int step = nums[i]; step >= 1; step--) {
            if (canReach(nums, i + step)) {
                return true;
            }
        }
        return false;
    }
}

Complexity

  • Time: O(2^n) in the worst case — overlapping subproblems are recomputed.
  • Space: O(n) — recursion depth.

Complexity Comparison

Approach Time Space
Brute Force Recursion O(2^n) O(n)
Bottom-Up DP O(n²) O(n)
Greedy O(n) O(1)

Common Pitfalls

  • Treating nums[i] as the exact jump length — it is the maximum; any shorter jump is allowed.
  • Forgetting the single-element array: you are already at the last index, so the answer is true.
  • Checking i > farthest after updating farthest — an unreachable index must not contribute its own jump.
  • Overflow is not an issue here (i + nums[i] <= 1.1 Ā· 10^5), but in similar problems with large values use long.