Jump Game

Question

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.

Example 1:

Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: nums = [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.

Solution

In this question, we return true if we can reach to the lastIndex. Therefore it makes sense to start from the goal and works backwards to see if we can reach the last index at the start.

For example we can denote 1 as reached to the last index and 0 is not reached.

Considering the following case:

 0 1 2 3 4 5 6
[1,7,2,0,0,0,1]

We can define another array [] to keep track of which node can reach to the lastIndex. Let's initialise it to all 0 — which means none of the node will reach the last index and works backwards.

 0 1 2 3 4 5 6
[1,7,2,0,0,0,1]
[0,0,0,0,0,0,0]

So at index 6 since it can reach our last index, we just simply define it as 1.

 0 1 2 3 4 5 6
[1,7,2,0,0,0,1]
[0,0,0,0,0,0,1]

Since our last known reachable index is 6, at index 5, we check if we can reach to our last known succesful index on its right (6). However since we have 0 as the value, 5 + 0 = 5, we cannot reach to 6. Therefore we mark it as 0

 0 1 2 3 4 5 6
[1,7,2,0,0,0,1]
[0,0,0,0,0,0,1]

Similar to 4, we cannot reach to 6 either so we mark it as 0. Same for 3.

At 2, the furthest index we can reach is 4. However 4 cannot go to index 6 so we also mark as 0.

At index 1, since 1 + 7 >= 6. Therefore we can reach to our last index, so we mark it as 1:

 0 1 2 3 4 5 6
[1,7,2,0,0,0,1]
[0,1,0,0,0,0,1]

Now at index 0, we check if we can reach to index 1 since index 1 can reach to the goal. In this case, since 0 + 1 >= 1. We mark index 0 as 1

 0 1 2 3 4 5 6
[1,7,2,0,0,0,1]
[1,1,0,0,0,0,1]

As a result, we return True since index 0 can reach the goal.

As you can see in here, the problem becomes at an index, checking if we can reach to the nearest 1 to the right.

To optimise this, we don't really need an array to keep track of 1 or 0. We can just have a lastReachableGoalIndex.

Implementation

class App:
    def canJump(self, nums: List[int]) -> bool:
        if not nums: raise Exception("Illegal arguments")
        lastReachableGoalIndex = len(nums) - 1
        
        for i in range(len(nums) - 1, -1, -1):
            if i + nums[i] >= lastReachableGoalIndex:
                lastReachableGoalIndex = i
        
        return lastReachableGoalIndex == 0

Time complexity: $O(n)$ — $n$ is length of nums
Space complexity: $O(1)$