Jump Game

Pattern: Jump game

medium

Walk left to right keeping the farthest index reachable. If the current index is beyond it, you are stuck. Otherwise extend it with i + nums[i]. Reaching the loop's end means the last index is reachable.

The problem

Starting at index 0, each value is the longest jump you may make from there. Return whether you can reach the last index. [2, 3, 1, 1, 4] is true; [3, 2, 1, 0, 4] is false.

Think first

  • Which indexes can you reach?
  • If you can reach index i, can you reach every index before it?
  • What single number describes everything reachable?

Hints

    Brute force, and why it fails

    Mark reachable indexes, trying every jump from each: O(n²).

    The key insight

    Reachable indexes form one prefix, so the farthest one is enough to track.

    Dry run

    20i
    31 
    12 
    13 
    44 
    farthest2

    nums = [2, 3, 1, 1, 4]. At 0: farthest = 2.

    Step 1 of 4

    The plan

    farthest = 0
    for i: if i > farthest: return false; farthest = max(farthest, i + nums[i])
    return true
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    One pass.

    Edge cases

    • One index: true.
    • A 0 at the start of a longer array: false.
    • Zeros that can be jumped over.
    I've built my logic, show the code

    Java

    class Solution {
        public boolean canJump(int[] nums) {
            int farthest = 0;                       // the farthest index reachable so far
            for (int i = 0; i < nums.length; i++) {
                if (i > farthest) return false;     // i itself cannot be reached
                farthest = Math.max(farthest, i + nums[i]);
            }
            return true;
        }
    }

    C++

    class Solution {
    public:
        bool canJump(vector<int>& nums) {
            long long farthest = 0;                 // the farthest index reachable so far
            for (int i = 0; i < static_cast<int>(nums.size()); i++) {
                if (i > farthest) return false;     // i itself cannot be reached
                farthest = max(farthest, static_cast<long long>(i) + nums[i]);
            }
            return true;
        }
    };

    Python

    class Solution:
        def canJump(self, nums: list[int]) -> bool:
            farthest = 0                            # the farthest index reachable so far
            for i, step in enumerate(nums):
                if i > farthest:
                    return False                    # i itself cannot be reached
                farthest = max(farthest, i + step)
            return True

    Common mistakes

    • Stopping at the first 0 even when it can be jumped over.
    • Checking only nums[i] > 0.

    Similar problems