## Similar Problems

Similar Problems not available

# Frog Jump Ii - Leetcode Solution

## Companies:

LeetCode: Frog Jump Ii Leetcode Solution

Difficulty: Medium

Topics: greedy binary-search array

Problem Statement:

Given an array of stones where stones[i] represents the position of the ith stone, you need to find the minimum number of jumps required to cross the stones. You start at the 0th stone and your final destination is the (n - 1)th stone.

You are allowed to make only the following jumps:

- You can jump from the ith stone to the (i + k - 1)th stone. Here, k is a constant value and represents the maximum length of a jump.
- You can jump from the ith stone to the (i + k)th stone. Here, k is a constant value and represents the maximum length of a jump.
- You can jump from the ith stone to the (i + k + 1)th stone. Here, k is a constant value and represents the maximum length of a jump.

You can only jump if the destination stone is not beyond the end of the array and is not in the water.

If it's not possible to reach the destination stone, return -1.

Solution Approach:

- The first step is to create a set containing all the stones that are in the array, this will ensure that we can check if we can jump to a certain stone.
- Then, we initialise a queue, where each element of the queue is a tuple containing the index of the stone and the number of jumps needed to reach that stone. Initially, we start with the 0th stone and 0 jumps.
- We then start a loop, where we pop the first element from the queue.
- We check if the current stone is the last stone, which is our destination. If it is, we return the number of jumps needed to reach that stone.
- We then generate all the possible jumps from that stone and check if the destination stone is in our set of stones.
- If the destination stone is in the set of stones, we add the tuple of the destination stone and the number of jumps needed to reach that stone to the queue.
- We repeat steps 3 to 6 until the queue is empty.
- If we reach the end of the loop and have not found a path to the destination stone, we return -1.

Code:

def frogJumpII(stones, k): stones_set = set(stones) queue = [(0, 0)] visited = set() while queue: current, jumps = queue.pop(0) visited.add(current) if current == stones[-1]: return jumps for i in range(1, k+2): next_jump = current + i if next_jump in stones_set and next_jump not in visited: queue.append((next_jump, jumps+1)) return -1

Time Complexity: O(n * k)

Space Complexity: O(n)

## Frog Jump Ii Solution Code

`1`