Lesson 39 of 73 1 min

Problem: Jump Game

Learn how to determine if you can reach the end of an array using the greedy "max reach" strategy.

Problem Statement

You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.

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

Approach: Maximum ReachABLE

Instead of exploring every possible jump (Backtracking $O(2^n)$), we track the furthest index we can currently reach.

  1. Iterate: Loop through the array.
  2. Unreachable: If the current index i > maxReach, it means we can't get here. Return false.
  3. Update: maxReach = max(maxReach, i + nums[i]).
  4. Success: If maxReach >= lastIndex, return true.

Java Implementation

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

Complexity Analysis

  • Time Complexity: $O(n)$. We pass through the array once.
  • Space Complexity: $O(1)$.

Interview Tips

  • Mention that this problem can also be solved with DP, but Greedy is the optimal $O(1)$ space solution.

Want to track your progress?

Sign in to save your progress, track completed lessons, and pick up where you left off.