(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.

Thoughts:
This is definitely do-able through recursion. I actually tried but got time exceed limit. So I came up with this iterative method with O(n^2) time complexity. We maintain a boolean table where table[i] stores whether you can reach the last index starting from index i. We start populating the table from the last position (n-1) of the array. We are at destination here so table[n-1] is always true. For each i, we look at all table values from i + 1 to n – 1. If we found a true value at j, we know we can reach the last index from j, so we just need to examine if we can reach index j from index i. If we can, then table[i] will be true and we don’t need to see the rest. In the worst case, for each i, we need to check every element from i + 1 to n – 1 so this is O(n^2).

Code (C++):

class Solution {
public:
    bool canJump(int A[], int n) {
        bool *table = new bool[n];
        table[n-1] = true;
        int start = n - 2;
        while(start >= 0) {
            table[start] = false;
            for(int j = start + 1; j < n; ++j) {
                if(table[j] && j - start <= A[start]) {
                    table[start] = true;
                    break;
                }
            }
            start--;
        }
        return table[0];
    }
};

Code (Java):

public class Solution {
    public boolean canJump(int[] A) {
        boolean[] table = new boolean[A.length];
        table[A.length-1] = true;
        int start = A.length - 2;
        while(start >= 0) {
            table[start] = false;
            for(int j = start + 1; j < A.length; ++j) {
                if(table[j] && j - start <= A[start]) {
                    table[start] = true;
                    break;
                }
            }
            start--;
        }
        return table[0];
    }
}

2 Comments (+add yours?)

  1. Trackback: (Jump Game II) « Runhe Tian Coding Practice
  2. superzankilifistic
    Nov 20, 2012 @ 16:58:35

    simple dp problem

    Reply

Leave a comment