Jump Game

[Jump Game]

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

[Analysis]

At first it seems like a straightforward DP problem and I did just that and failed at the last test cases which contains 25k elements… Lessons learned, there must be some observations to be made in order to optimize the solution. Let’s optimize it!

Note my DP array canJump. In fact, we know there are maximum n steps that we can make on each given position i, therefore the n steps following the positions i are all possible destinations. That is, note how our DP array is set block by block, this means that if we have canJump[i] = true, not only position i is a possible destination, but every elements before it must also be possible destinations. There is thus no need to set them to true again.

Therefore, at each position, we retain previously farthest position such that canJump[farthest] = true, we check if i+A[i] would bring us even farther, if yes, we start at farthest and update our farthest position. The complexity is thus brought to O(n) instead of O(n^2), because we only set each elements to true once, so in total we are still in O(n).

    bool canJump(int A[], int n) {
        if (n == 0)
            return false;
            
        bool canJump[n];
        
        for (int i=0; i<n; ++i){
            canJump[i] = false;
        }
        
        canJump[0] = true;
        int farthest = 0;
        
        
        for (int i=0; i<n; ++i) {
            if (canJump[i]) {
                if (i+A[i] > farthest) {
                    for (int j=farthest; j<n-1 && j<=i+A[i]; ++j) {
                        canJump[j] = true;
                    }
                    farthest = min(n-1, i+A[i]);
                    if (farthest == n-1)
                        return true;
                } 
            }
        }
        
        return canJump[n-1];
    }

Update:
Turns out there is even no need for the DP part, since we know everything before farthest is attainable, why not just check if i<=farthest? This runs in 20ms instead of 70ms. Not so bad 😛


    bool canJump(int A[], int n) {
        if (n == 0)
            return false;
        if (n == 1)
            return true;

        int farthest = 0;

        for (int i=0; i<n; ++i) {
            if (i <= farthest) {
                if (i+A[i] > farthest) {
                    farthest = min(n-1, i+A[i]);
                    if (farthest == n-1)
                        return true;
                }
            }
        }

        return false;
    }

Leave a comment