Skip to problem
←

Frog Jump

Hard 0 attempts

A frog needs to cross a river that's divided into evenly spaced units, some of which have stones. You're given the positions of the stones as a sorted array stones, with the frog beginning on the stone at position 0 and required to make its very first jump exactly 1 unit forward. After a jump of k units, its next jump must measure k-1, k, or k+1 units, and it can only ever jump forward. Determine whether the frog is able to reach the final stone.

Function contract

stones contains distinct stone positions in strictly increasing order, starting at 0.

Output: Return true if the frog can land on the final stone under the jump rules, otherwise false.

Example 1

Input
stones = [0,1,3,5,6,8,12,17]
Output
true

Explanation: One valid route is 0 → 1 → 3 → 5 → 8 → 12 → 17, using jumps 1, 2, 2, 3, 4, 5.

Example 2

Input
stones = [0,1,2,3,4,8,9,11]
Output
false
Constraints
  • 2 <= stones.length <= 2000
  • 0 <= stones[i] <= 2^31 - 1
  • stones[0] == 0
  • stones is strictly increasing (no duplicate positions).

Approach: DP with HashMap

Map each stone position to a set of possible jump sizes that can reach it. Starting from stone 0 with jump 0, for each stone try jumps of k-1, k, and k+1. If the destination exists, add the jump size to that stone's set.

javascript
function frogJump(stones) {
  const map = new Map();
  for (const s of stones) map.set(s, new Set());
  map.get(0).add(0);
  for (const s of stones) {
    for (const k of map.get(s)) {
      for (const jump of [k-1, k, k+1]) {
        if (jump > 0 && map.has(s + jump)) map.get(s + jump).add(jump);
      }
    }
  }
  return map.get(stones[stones.length - 1]).size > 0;
}

Time Complexity: O(n²)

Space Complexity: O(n²)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript