
Assume the first jump to be 1 unit.
You can jump only on a stone.
You are given ‘stones’ = [0, 1, 3, 5], in this array you can go from 0 -> 1 (1 unit), then from 1 -> 3 (2 units), 3 -> 5 (2 units). Hence the answer is True.
The first line of input contains a single integer ‘T’ representing the number of test cases.
The first line of each test case contains a single integer ‘N’ representing the size of the array.
The second line of each test case contains ‘N’ space-separated integers representing the elements of the array.
For each test case, return True if you can reach the last stone, else return False.
Print a separate line for each test case.
1 <= T <= 10
2 <= N <= 10^3
1 <= stones[i] <= 10^9
stones[0] = 0
Time Limit: 1 sec.
You do not need to print anything. It has already been taken care of. Just implement the given function.
In this approach, at each step, we will keep track of the last step taken and try all possible next steps. If any of the steps return true, then the current step will also return true.
We create a set postionSet to check if the current position is present in the stones array.
We will create a recursive function, possiblePositions(stones, currPos, positionSet, lastStep), where ‘stones’ is the array given, currPos is the current position we are checking, positionSet is the set of all positions, and lastStep is the last step taken.
Algorithm:
In this approach, we will use the same method as earlier and we will create a cache to not repeat the recursion steps and minimize the time complexity. Instead of storing all the positions in a set will store the positions in a map, with value as the index in the stones array.
We will create a recursive function, possiblePositions(stones, currPos, positionMap, lastStep, cache), where ‘stones’ is the array given, currPos is the current position we are checking, positionMap is the map of all positions, mapped to their index in stones array, and lastStep is the last step taken.
In this approach, at the current step, we will try to calculate the set of all possible steps taken to reach the current step. We will create a map ‘steps’ where steps[i] is the set of all steps taken to reach ‘ith’ position.
Then for each position, we will iterate through all possible steps to get there and calculate the next steps.
Algorithm: