Similar Problems

Similar Problems not available

Jump Game Vii - Leetcode Solution

Companies:

LeetCode:  Jump Game Vii Leetcode Solution

Difficulty: Medium

Topics: string sliding-window dynamic-programming prefix-sum  

The Jump Game VII problem on LeetCode asks us to determine whether we can reach the last index of an array by performing jumps, where each jump's length is either fixed or within a certain range.

Given an array of integers nums, two integer values minJump and maxJump determine the minimum and maximum range of the jump from index i, respectively. You start at the index 0 of the array and are required to reach the last index of the array.

The problem statement asks us to return True if you can reach the last index and False otherwise.

Approach:

This problem can be solved using a sliding window. We can iterate through the entire array and for each element, we can build a count of the number of indices that can be reached from that index. We can then use this information to determine whether we can reach the last index or not.

To build the count for each index, we can start from index 0 and iterate through the array up to the current index i. For each index j within the range [i-minJump, i-maxJump], if nums[j] is non-zero, we can increment the count for index i.

After we have built the count for each index, we can use it to traverse the array from index 0 to n-1. We can start from index 0, and for each index i, we can check whether there is at least one index within the range [i+1, i+count[i]] that can be reached. If there is, we can continue to the next index; otherwise, we have reached a dead end and we cannot move any further. In this case, we can return False.

If we reach the last index, we can return True.

Time Complexity:

The worst-case time complexity of this algorithm is O(n^2), where n is the length of the input array. This worst-case occurs when minJump is 1 and maxJump is n-1, resulting in a sliding window of size n-1.

Space Complexity:

The space complexity of this algorithm is O(n), where n is the length of the input array. This space is used to store the count of the number of indices that can be reached from each index.

Solution:

Here is the Python implementation of the above approach:

def canReach(nums, minJump, maxJump): n = len(nums) count = [0] * n count[0] = 1

for i in range(1, n):
    for j in range(i - maxJump, i - minJump + 1):
        if j >= 0 and nums[j] != 0:
            count[i] += count[j]
            
for i in range(n):
    if nums[i] != 0 and i + minJump <= n and count[i] > 0:
        for j in range(i + minJump, min(i + maxJump + 1, n)):
            if nums[j] != 0 and count[j] > 0:
                return True
            
return False

print(canReach([4,2,3,0,3,1,2], 2, 3))

Output:

True

LeetCode Problem Link:

https://leetcode.com/problems/jump-game-vii/

Jump Game Vii Solution Code

1