[LeetCode] Jump Game and Jump Game II (Java)

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.

Jump Game II

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.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

Analysis

In Jump Game, we can save the farthest position we can reach when we go through the array. Every time we move, we will decrease the step. When we updating it, the step remaining for us is also updated. For example, for array A = [2, 3, 1, 1, 4], when we visit A[0], we update the maxReach to 2, and step to 2. When we visit A[1], we update maxReach to 1 + 3 = 4. And step is updated to 3. We will continue doing this until we reach the end or step getting to zero. If step getting to zero before we reach the end, it means that we can’t move forward so that we should return false.

In Jump Game II, we are asked for the minimum number of jumps. In fact, we only needs the number of jumps but not the path we jump. So that we can modify the code in Jump Game. We do not update step when we find a further position that we can reach. We only update it when step getting to 0. It means we can find the minimum number of jumps. In fact, in the test cases of this problem we can always reach the end. If we need to output -1 if we cannot reach the end, the code should be modified a little.

Code

Jump Game

Jump Game II

Complexity

We only go through the array once. So the complexity is only $O(n)$.

  • Hamid

    I have been looking for a good understanable solution and I stumbled upon yours. I think it’s pretty impressive that how you make a complicated problem look so easy to code. great job!

  • Prabhat Meghwal

    Gives wrong output on A : [ 0, 46, 46, 0, 2, 47, 1, 24, 45, 0, 0, 24, 18, 29, 27, 11, 0, 0, 40, 12, 4, 0, 0, 0, 49, 42, 13, 5, 12, 45, 10, 0, 29, 11, 22, 15, 17, 41, 34, 23, 11, 35, 0, 18, 47, 0, 38, 37, 3, 37, 0, 43, 50, 0, 25, 12, 0, 38, 28, 37, 5, 4, 12, 23, 31, 9, 26, 19, 11, 21, 0, 0, 40, 18, 44, 0, 0, 0, 0, 30, 26, 37, 0, 26, 39, 10, 1, 0, 0, 3, 50, 46, 1, 38, 38, 7, 6, 38, 27, 7, 25, 30, 0, 0, 36, 37, 6, 39, 40, 32, 41, 12, 3, 44, 44, 39, 2, 26, 40, 36, 35, 21, 14, 41, 48, 50, 21, 0, 0, 23, 49, 21, 11, 27, 40, 47, 49 ]