Taro Logo

Frog Jump

#67 Most AskedHard
0 views
Topics:
ArraysDynamic Programming

A frog is crossing a river. The river is divided into some number of units, and at each unit, there may or may not exist a stone. The frog can jump on a stone, but it must not jump into the water.

Given a list of stones positions (in units) in sorted ascending order, determine if the frog can cross the river by landing on the last stone. Initially, the frog is on the first stone and assumes the first jump must be 1 unit.

If the frog's last jump was k units, its next jump must be either k - 1, k, or k + 1 units. The frog can only jump in the forward direction.

Example 1:

Input: stones = [0,1,3,5,6,8,12,17]
Output: true
Explanation: The frog can jump to the last stone by jumping 1 unit to the 2nd stone, then 2 units to the 3rd stone, then 2 units to the 4th stone, then 3 units to the 6th stone, 4 units to the 7th stone, and 5 units to the 8th stone.

Example 2:

Input: stones = [0,1,2,3,4,8,9,11]
Output: false
Explanation: There is no way to jump to the last stone as the gap between the 5th and 6th stone is too large.

Constraints:

  • 2 <= stones.length <= 2000
  • 0 <= stones[i] <= 231 - 1
  • stones[0] == 0
  • stones is sorted in a strictly increasing order.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum number of stones in the array (array length), and what is the maximum possible position value of the last stone?
  2. Can the input array contain duplicate stone positions?
  3. Is the first stone always located at position 0, and is the frog's initial jump size strictly fixed at 1 unit from the first stone to the second?
  4. What should be returned if the array is empty, has only one element, or if the first jump of 1 unit cannot even reach the second stone?
  5. If multiple valid jump sequences can reach the final stone, do we only need to return a boolean indicating whether any successful path exists, or do we need to account for multiple valid paths?

Brute Force Solution

Approach

Imagine a frog trying to cross a river by hopping from stone to stone, where each hop can be slightly different in size. The brute force approach involves exploring every single path of hops the frog could possibly take until it either gets stuck or reaches the final stone.

Here's how the algorithm would work step-by-step:

  1. Start the frog at the very first stone, where its first hop must be a specific tiny distance forward.
  2. Look at all the stones that happen to be at the exact right distances away based on the current hop size and the allowed rule changes.
  3. Pick one of those reachable stones and pretend the frog jumps to it.
  4. From that new stone, calculate the new possible jump sizes and repeat the process of trying every available forward path.
  5. If the frog lands on a stone and finds there are no valid stones left to reach, acknowledge that this particular path is a dead end.
  6. Backtrack to the previous stone and try a different hop size to explore a completely new sequence of jumps.
  7. Keep trying every conceivable combination of hops until the frog successfully touches the final stone, proving that crossing is possible.

Code Implementation

class Solution:
    def canCross(self, stones: list[int]) -> bool:
        
        stone_positions = set(stones)
        final_stone = stones[-1]
        
        # We memoize paths to prevent redundant recursive calculations on dead ends
        memoization_cache = set()
        
        def recursive_depth_first_search(current_position, current_jump_size):
            if current_jump_size <= 0:
                return False
                
            if current_position == final_stone:
                return True
                
            state_identifier = (current_position, current_jump_size)
            if state_identifier in memoization_cache:
                return False
                
            # We test all three variation paths for the next hop size rule
            for next_jump_size in (current_jump_size - 1, current_jump_size, current_jump_size + 1):
                if next_jump_size > 0:
                    next_position = current_position + next_jump_size
                    if next_position in stone_positions:
                        if recursive_depth_first_search(next_position, next_jump_size):
                            return True
                            
            # We cache failed states so we never re-evaluate identical dead ends
            memoization_cache.add(state_identifier)
            return False
            
        if len(stones) > 1 and stones[1] != 1:
            return False
            
        return recursive_depth_first_search(0, 0)

Big(O) Analysis

Time Complexity
O(n²) – In this frog jump problem, the input size n represents the total number of stones in the river. The cost is driven by exploring potential jump states, where each of the n stones can be reached with up to n distinct incoming jump sizes. For each stone, we iterate through its possible jump sizes and look up reachable next stones in a hash map. Across the entire recursive exploration, this results in approximately n * n operations because each stone-jump state is evaluated at most once. Simplifying this total operation count yields a final time complexity of O(n²).
Space Complexity
O(n^2) – The space complexity is driven by the state tracking and the recursive call stack needed to explore every valid path. Specifically, we store reachable jump sizes for each of the N stones in a lookup structure, which in the worst case can hold a number of state combinations proportional to N squared. Additionally, the backtracking recursion stack can grow up to a depth of N as the frog traverses the stones. Combining these factors yields a total auxiliary space complexity that scales quadratically with the number of stones.

Optimal Solution

Approach

Instead of blindly testing every possible sequence of jumps, the optimal strategy remembers the exact size of the previous jump made at each resting spot. By keeping track of what previous jump sizes are possible at every location, the strategy avoids repeating work and quickly determines if the final destination is reachable.

Here's how the algorithm would work step-by-step:

  1. Begin at the starting stone with a jump size of zero and record that this location has been reached.
  2. Move forward to the next reachable stone, noting the exact size of the jump required to get there.
  3. At this new stone, figure out all the valid jump sizes you could make next, which include the previous jump size minus one, the exact same previous jump size, or the previous jump size plus one.
  4. Check if any of those valid next jump sizes allow you to land on a further stone ahead.
  5. Record the arrival at those further stones along with the specific jump sizes used to reach them.
  6. Repeat this tracking process for every stone you successfully visit, making sure never to repeat work for a stone and jump size combination you have already checked.
  7. Finally, check whether any valid sequence of jumps successfully lands on the very last stone in the river.

Code Implementation

class Solution:
    def canCross(self, stones: list[int]) -> bool:
        stone_positions = {stone: index for index, stone in enumerate(stones)}
        
        jump_tracking_map = {stone: set() for stone in stones}
        jump_tracking_map[stones[0]].add(0)
        
        # We iterate through each stone to evaluate possible forward jumps from current positions.
        for stone_index, current_stone in enumerate(stones):
            for previous_jump_size in jump_tracking_map[current_stone]:
                for delta_adjustment in [-1, 0, 1]:
                    next_jump_size = previous_jump_size + delta_adjustment
                    
                    if next_jump_size > 0:
                        target_stone = current_stone + next_jump_size
                        
                        if target_stone in stone_positions:
                            jump_tracking_map[target_stone].add(next_jump_size)
                            
        # We check if any valid jump sequence successfully reached the final destination stone.
        return len(jump_tracking_map[stones[-1]]) > 0

Big(O) Analysis

Time Complexity
O(n²) – Let n be the number of stones in the river. For each stone we visit, we iterate through its stored set of possible incoming jump sizes, and at most, we evaluate three potential next jump sizes to find further stones. Since a stone can be reached with at most n distinct jump sizes, we process at most n states for each of the n stones. This yields approximately n * n operations in the worst case, which simplifies to O(n²).
Space Complexity
O(n^2) – To track visited locations and their possible previous jump sizes as described in the strategy, the algorithm utilizes a hash map or set data structure for each of the N stones. In the worst-case scenario, every stone can be reached by up to N distinct jump sizes, leading to roughly N squared stored state combinations. Therefore, the auxiliary space scales quadratically with respect to the input size N of stones in the river.

Edge Cases

Input array is empty or null
How to Handle:
Return false immediately as there are no stones to cross.
Input array has only one element
How to Handle:
Return true immediately since the frog starts on the final stone.
The second stone is not at position 1
How to Handle:
Return false because the frog's first mandatory jump size of 1 cannot land on the second stone.
Large input size with maximum possible stone positions
How to Handle:
Use memoized dynamic programming or a hash set to avoid exponential time complexity and prevent stack overflow.
Gaps between stones are too large for any valid jump sequence
How to Handle:
The algorithm will exhaust all valid jump branches and correctly return false.
Stones are densely packed with multiple valid paths to the end
How to Handle:
Memoization ensures overlapping subproblems are computed only once, maintaining optimal efficiency.
Large jump distances causing integer overflow
How to Handle:
Use standard 32-bit or 64-bit signed integers since stone positions fit well within standard integer limits.
Input array has duplicate stone positions
How to Handle:
Store valid jump states per stone index in a hash map to correctly process multiple identical positions.
0/257 completed