Array Hopper I

Given an array of non-negative integers, you are 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.

Ex:

[2,3,1,1,4] returns true

[3,2,1,0,4] returns false

Solution: DP approach with helper array

Base Case: M[n-1] = true

Inductive Rule: Check array backwards

For each index, in back to front order

Case 1: itself has enough jumps to reach goal

Case 2: it can reach another index that can reach goal

Case 3: it can not reach goal nor reach another index that can

return M[0]

public class Solution {
  public boolean canJump(int[] array) {
    boolean[] M = new boolean[array.length];
    M[array.length - 1] = true;
    int closestTrue = array.length - 1;
    for (int i = array.length - 2; i >= 0; i--){
      int jumpLen = array[i];
      if (i + jumpLen >= closestTrue){
        M[i] = true;
        closestTrue = i;
      }
    }
    return M[0];
  }
}

TC: One pass back to front O(N)

SC: M[].length = array.length O(N)

Last updated

Was this helpful?