Frog Jump - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: stones = [0,1,3,5,6,8,12,17]
Output: true
💡 Note: Frog can jump: 0→1 (jump 1), 1→3 (jump 2), 3→5 (jump 2), 5→6 (jump 1), 6→8 (jump 2), 8→12 (jump 4), 12→17 (jump 5)
Example 2 — Impossible Case
$ Input: stones = [0,1,2,3,4,8,9,11]
Output: false
💡 Note: Gap from stone 4 to stone 8 is too large - frog cannot jump 4 units as maximum jump from position 4 would be 3 units
Example 3 — Edge Case
$ Input: stones = [0,1,3,6,10,15]
Output: true
💡 Note: Path exists: 0→1 (jump 1), 1→3 (jump 2), 3→6 (jump 3), 6→10 (jump 4), 10→15 (jump 5)

Constraints

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

Visualization

Tap to expand
Frog Jump Problem - Dynamic Programming INPUT River (units 0-17) 0 1 3 5 6 8 12 17 stones array: 0 1 3 5 6 8 12 17 Jump Rules: - First jump = 1 unit - If last jump = k units - Next: k-1, k, or k+1 - Forward direction only Goal: Reach stone at position 17 ALGORITHM STEPS 1 Create DP Map Map: stone pos --> set of possible jump sizes 2 Initialize dp[0] = {0} (start pos) First jump must be 1 3 Process Each Stone For each k in dp[stone]: Try jumps k-1, k, k+1 4 Check Reachability Return dp[last_stone] is not empty DP State Tracking dp[0] = {0} dp[1] = {1} dp[3] = {2} dp[5] = {2} dp[6] = {1,3} dp[8] = {2,3} dp[12] = {4} dp[17] = {5} FINAL RESULT Successful Jump Path: 0 1 3 5 8 12 17 k=1 k=2 k=2 k=3 k=4 k=5 Jump Sequence: 0 --1--> 1 --2--> 3 --2--> 5 5 --3--> 8 --4--> 12 --5--> 17 Output: true [ OK ] Frog reaches last stone! Path found: 6 jumps total Jump sizes: 1, 2, 2, 3, 4, 5 Key Insight: Use a HashMap where each stone position maps to a set of possible jump sizes that can reach it. For each stone, try all valid next jumps (k-1, k, k+1) and add the jump size to the target stone's set. Time: O(n^2), Space: O(n^2) - where n is the number of stones. TutorialsPoint - Frog Jump | Dynamic Programming Approach
Asked in
Google 45 Amazon 32 Facebook 28 Microsoft 25
67.0K Views
High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen