Advertisement
Home Data Structure Arrays Check if an Array can be Jumped to the End

Check if an Array can be Jumped to the End

0
Advertisement

Title: Check if an Array can be Jumped to the End

In this guide, you’ll learn how to check whether an array of jump lengths lets you reach the last index, starting from the first. This is the classic Jump Game interview question, and it has a clean greedy solution that runs in a single pass over the array.

We’ll walk through the problem statement, build a full Java program, trace it by hand on a concrete input, and then cover the mistakes, edge cases, and follow-up questions interviewers actually ask about this problem.

Understanding the Problem

You are given an array of non-negative integers called nums, where each element nums[i] represents the maximum number of steps you can jump forward from index i. Starting at index 0, you need to determine whether it is possible to reach the last index of the array using some sequence of jumps.

You don’t need to find the actual sequence of jumps, only whether the last index is reachable at all. For example, [2, 3, 1, 1, 4] is reachable (jump 1 step, then 3 steps), but [3, 2, 1, 0, 4] is not, because every path gets stuck at the 0.

Approach

  1. Handle the trivial case first: if nums has 0 or 1 elements, the starting position is already the end, so return true.
  2. Initialize maxReach to 0, representing the farthest index reachable so far.
  3. Iterate i from 0 to nums.length - 1.
  4. At each index, check whether i is already beyond maxReach. If it is, no earlier jump could get you this far, so return false.
  5. Otherwise, update maxReach to Math.max(maxReach, i + nums[i]), extending the frontier if this index’s jump reaches farther than anything seen before.
  6. If maxReach already covers the last index, return true immediately without finishing the loop.
  7. After the loop completes, return whether maxReach is at least nums.length - 1.

Java Program

Java
public class ArrayJumpToEnd {

    public static boolean canJumpToEnd(int[] nums) {
        if (nums == null) {
            throw new IllegalArgumentException("nums must not be null");
        }
        int n = nums.length;
        if (n <= 1) {
            return true;
        }

        int maxReach = 0;
        for (int i = 0; i < n; i++) {
            if (i > maxReach) {
                return false;
            }
            maxReach = Math.max(maxReach, i + nums[i]);
            if (maxReach >= n - 1) {
                return true;
            }
        }
        return maxReach >= n - 1;
    }

    public static void main(String[] args) {
        int[] nums1 = {2, 3, 1, 1, 4};
        System.out.println(canJumpToEnd(nums1));

        int[] nums2 = {3, 2, 1, 0, 4};
        System.out.println(canJumpToEnd(nums2));
    }
}

Explanation of the Program

The method canJumpToEnd first checks for a null array and for arrays of length 0 or 1, since those cases need no jumps at all.

Inside the loop, maxReach always holds the farthest index that any jump taken so far could land on. The check i > maxReach catches the moment the current index has outrun every jump before it, which means the array is unreachable from here.

When a jump extends the frontier, maxReach = Math.max(maxReach, i + nums[i]) keeps only the single best option seen so far, which is why the algorithm never needs to try every possible combination of jumps.

The early return once maxReach >= n - 1 is an optimization. It stops scanning the rest of the array the moment the goal is already guaranteed.

Step-by-Step Trace

Trace canJumpToEnd on nums = [2, 0, 0, 0, 1, 4]. The target is index 5, and the run of zeros in the middle should block the path.

Iteration (i)nums[i]maxReach (before)i > maxReach?maxReach (after) / Result
020no2
102no2 (no change)
202no2 (no change)
302yesstuck, return false

At the start of each iteration, maxReach holds the farthest index reachable using only the jumps taken so far. The moment i exceeds that frontier, as happens at i = 3 above, no sequence of earlier jumps can carry you any further, so the method returns false immediately.

Examples

Example 1: A Reachable Array

A mix of small jumps still reaches the end because no single gap is ever wider than the frontier built up so far.

Java
int[] nums = {2, 3, 1, 1, 4};
System.out.println(canJumpToEnd(nums));
// Output: true

Example 2: Blocked by a Zero

The 0 at index 3 caps maxReach at 3 before the loop ever gets there, so index 4 is never reachable.

Java
int[] nums = {3, 2, 1, 0, 4};
System.out.println(canJumpToEnd(nums));
// Output: false

Example 3: One Jump Covers Everything

A large first jump can make the rest of the array irrelevant, even if every later value is 0.

Java
int[] nums = {5, 0, 0, 0, 0};
System.out.println(canJumpToEnd(nums));
// Output: true

Common Mistakes to Avoid

These are the slips that most often turn a correct idea into a wrong answer on this specific problem.

  • Treating nums[i] as a step counter to decrement – subtracting one from a shared counter at every index throws away information once a later, larger jump value appears, wrongly rejecting reachable arrays like [2, 3, 1, 1, 4]. Recompute maxReach = Math.max(maxReach, i + nums[i]) at every index instead.
  • Using i >= maxReach instead of i > maxReach – this wrongly flags arrays like [2, 0, 0] as unreachable, because standing exactly on the frontier index is still valid. Use the strict i > maxReach check, since being exactly at the frontier means you are still reachable.
  • Skipping the length-0 or length-1 short-circuit – feeding a single-element array straight into the main loop works by accident here, but omitting the check becomes a real bug the moment the loop body is changed to assume at least one jump is made. Return true immediately when nums.length <= 1.
  • Recursing over every possible jump length - a brute-force solution that tries each jump size from every index is correct but explores exponentially many paths, so it times out or overflows the call stack on arrays with a few hundred elements. Use the greedy max-reach approach to answer the question in a single linear pass.

Edge Cases to Test

Walk through these inputs before calling the problem solved, since each one exercises a different branch of the greedy check.

  • Empty array
  • Single-element array
  • Leading zero with length greater than 1 (nums[0] == 0)
  • Zeros clustered in the middle of the array
  • First jump value large enough to cover the entire array
  • All jump values equal to 1
  • Jump value near Integer.MAX_VALUE that could overflow i + nums[i]
  • Null array reference

Additional Considerations

The greedy scan runs in O(n) time, since it visits each index at most once and does a constant amount of work per index. It uses O(1) extra space, because maxReach is the only state carried between iterations.

A brute-force recursive solution that tries every jump length from every index runs in exponential time, and a dynamic programming version that marks each index as reachable or not improves that to O(n^2) in the worst case. Neither is necessary here, because the greedy frontier argument guarantees that tracking only the single farthest reachable index is enough to answer the question correctly.

On arrays with very large nums[i] values, i + nums[i] can overflow a 32-bit int if the jump value is close to Integer.MAX_VALUE. Clamping maxReach to nums.length - 1 as soon as it would exceed the array bounds avoids relying on overflow behavior.

Interview Follow-up Questions

Once you've shown the base solution, expect an interviewer to push on these variations to see how far your approach generalizes.

  • What if you need the minimum number of jumps to reach the end, not just whether it is possible? - layer the array into reachable levels and increment a jump counter whenever the current frontier must be extended; this is the classic Jump Game II.
  • What if each index also has a cost to land on, and you want the cheapest reachable path? - the simple greedy frontier no longer applies. Switch to a shortest-path formulation such as Dijkstra's algorithm or dynamic programming over reachable indices.
  • What if you must solve it using only O(1) extra memory and no recursion? - the max-reach approach already satisfies this, since it tracks only a single running integer alongside the loop index.
  • What if you need to reconstruct one actual sequence of jumps, not just a yes or no answer? - record which index produced each new maxReach value, then walk that chain of records backward once you confirm the end is reachable.
  • What if the array arrives as an unbounded stream and you must answer 'reachable so far' after every new element? - keep updating maxReach as each value streams in and compare it against the current known length, since there is no fixed array bound to check against up front.

Conclusion

Checking whether an array can be jumped to the end comes down to tracking one number, the farthest index reachable so far, and bailing out the moment the current index outruns it. That single insight turns an exponential brute-force search into a linear, constant-space scan.

Try adapting the code in this guide to return the minimum number of jumps instead of a boolean, or to reconstruct the jump path itself. You can learn more about array-based problems like this one on the Arrays category page.