Tutorialspoint
Problem
Solution
Submissions

Frog Jump

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to determine if a frog can cross a river by jumping on stones. The frog starts on the first stone and wants to reach the last stone. The frog can only jump forward and the jump distance must be k-1, k, or k+1 units, where k is the distance of the previous jump. Initially, the frog jumps 1 unit from the first stone.

Example 1
  • Input: stones = [0,1,3,5,6,8,12,17]
  • Output: true
  • Explanation:
    Frog starts at stone 0 and jumps 1 unit to stone 1.
    From stone 1, frog can jump 1 or 2 units. Jump 2 units to stone 3.
    From stone 3, frog can jump 1, 2, or 3 units. Jump 2 units to stone 5.
    Continue this pattern until reaching the last stone.
Example 2
  • Input: stones = [0,1,2,3,4,8,9,11]
  • Output: false
  • Explanation:
    Frog starts at stone 0 and jumps to stone 1.
    From stone 1, frog can reach stone 2 or stone 3.
    The gap between stones 4 and 8 is too large.
    No valid sequence of jumps can reach the last stone.
Constraints
  • 2 ≤ stones.length ≤ 2000
  • 0 ≤ stones[i] ≤ 2^31 - 1
  • stones[0] == 0
  • stones is sorted in ascending order
  • Time Complexity: O(n^2)
  • Space Complexity: O(n^2)
ArraysDynamic Programming Goldman SachsTutorix
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use dynamic programming with memoization to track possible jump distances
  • For each stone, maintain a set of possible jump distances that can reach it
  • From each stone, try jumps of k-1, k, and k+1 units where k is the previous jump
  • Use a 2D array or hash map to store stone positions and possible jump distances
  • Start with the first stone having a possible jump distance of 1
  • Return true if the last stone can be reached with any valid jump distance

Steps to solve by this approach:

 Step 1: Create a 2D DP table where dp[i][j] represents if stone i can be reached with jump distance j
 Step 2: Initialize the base case: first stone can be reached with jump distance 1
 Step 3: For each stone and each possible jump distance, check if it's reachable
 Step 4: From each reachable state, try jumps of k-1, k, and k+1 units
 Step 5: Find the next stone position and update the DP table accordingly
 Step 6: Check if the last stone is reachable with any valid jump distance
 Step 7: Return true if any path exists to the last stone, false otherwise

Submitted Code :