Frog Jump
Hard
Topics
A frog crosses a river by hopping on stones. The array nums gives the sorted positions of the stones (in units). The frog starts on the first stone (position 0) and its first jump must be exactly 1 unit. If the last jump was k units, the next jump must be k-1, k, or k+1 units and must be strictly positive. Return true if the frog can land on the last stone.
Example 1
Input: stones = [0,1,3,5,6,8,12,17] Output: true
Example 2
Input: stones = [0,1,2,3,4,8,9,11] Output: false
Constraints
- 2 <= nums.length <= 2000
- 0 <= nums[i] <= 2^31 - 1
- nums[0] == 0 and nums is strictly increasing.
Editorial — intuition, approach, complexity and pitfalls
Intuition
The frog's next jump is k-1, k or k+1 where k was the last jump. So "which stone am I on" is not enough state to decide anything — arriving at stone 6 with a last jump of 1 gives you different options than arriving with a last jump of 3. The state is the pair (stone, last jump size).
Plain recursion over that pair explores the same pairs repeatedly along different routes, which is exponential. Memoising the pair is the fix, and once you memoise you may as well build it forwards: for each stone, record the set of jump sizes that can land on it.
Why a set rather than a single best value: there is no "best" last jump. A larger jump reaches further but a smaller one can be more useful if the next gap is small, and neither dominates. So every arriving jump size has to be kept — this is the thing that makes the problem Hard rather than a routine DP.
Two bounds keep it tractable. Jump sizes are positive, so k-1 is discarded when it would be zero or less. And from stone i the last jump cannot exceed i, because reaching the i-th stone takes at least i jumps each of size at least 1 — so each stone holds at most O(n) distinct jump sizes, giving an O(n^2) bound overall.
Membership is by stone position, not index, so a hash map from position to index turns "is there a stone at stones[i] + step" into an O(1) lookup. Without it every probe would be a binary search and the whole thing becomes O(n^2 log n).
Approach
- Build
pos, a map from stone position to its index. dp[i]is the set of jump sizes that can land on stonei. Seeddp[0] = {0}— the frog starts on stone 0 having jumped nothing. The first jump must therefore be0+1 = 1, which matches the rule that the first jump is always 1.- Sweep stones left to right. For each arriving jump size
k, tryk-1,k,k+1; for each positive step landing on an existing stone, add that step to the target's set. - The last stone is reachable if its set is non-empty.
Sweeping forward is safe because every jump moves strictly right, so dp[i] is complete before stone i is processed.
Dry Run
stones = [0,1,3,5,6,8,12,17], expected true.
stone 0, arrived k=0 -> steps 1 only reaches 1 (k=1)
stone 1, arrived k=1 -> steps 1,2 reaches 3 (k=2) [2 lands on 3]
stone 3, arrived k=2 -> steps 1,2,3 reaches 5 (k=2), 6 (k=3)
stone 5, arrived k=2 -> steps 1,2,3 reaches 6 (k=1), 8 (k=3)
stone 6, arrived k=1 -> steps 1,2 reaches 8 (k=2)
stone 6, arrived k=3 -> steps 2,3,4 reaches 8 (k=2)
stone 8, arrived k=3 -> steps 2,3,4 reaches 12 (k=4)
stone 12, arrived k=4 -> steps 3,4,5 reaches 17 (k=5)
dp[17] = {5}, non-empty -> trueStone 6 is the instructive one: it is reached twice, with k=1 and with k=3, and both are kept. Stone 8 is reachable from either. Had we stored only the largest arriving jump, stone 6 would hold {3} and the route through k=1 would be invisible — on a different stone layout that is exactly how a greedy loses a valid path.
Complexity
- Time — O(n^2): at most O(n) jump sizes per stone, three transitions each, every lookup O(1) through the position map. At the constraint limit of 2000 stones that is about 4 million set operations.
- Space — O(n^2): the sets, in total up to one entry per (stone, jump size) pair, plus O(n) for the position map. This can be trimmed in practice — a set per stone of only the sizes actually seen is far smaller than the bound on real inputs — but the worst case stands.
Common Pitfalls
- Using the stone index as the jump size, or mixing the two. Jumps are measured in position units while
dpis indexed by stone number, and the two coincide only on contiguous layouts. - Keeping one value per stone instead of a set. No single arriving jump dominates, so collapsing the set loses reachable routes.
- Allowing a step of 0 or negative.
k-1must be filtered; a zero jump would let the frog sit still forever and report success. - Seeding
dp[0]with 1 rather than 0. With 0 the first jump comes out as 1 from the general rule; seeding 1 lets the first jump be 2, which the problem forbids. - Searching for the next stone by scanning or binary searching. The position map is what holds the bound at O(n^2); without it there is an extra log factor for no reason.
- Assuming the frog must land on the last stone from the stone immediately before it. It may arrive from any earlier stone whose jump sequence works out.
- Forgetting that positions can reach 2^31 - 1. The positions themselves are fine in 32-bit, but anything that sums them is not.
Full Solution — all languages
class Solution:
def canCross(self, nums):
stones = nums
n = len(stones)
if n == 1:
return True
pos = {s: i for i, s in enumerate(stones)}
dp = [set() for _ in range(n)]
dp[0].add(0)
for i in range(n):
for k in list(dp[i]):
for step in (k - 1, k, k + 1):
if step > 0:
nxt = stones[i] + step
if nxt in pos:
dp[pos[nxt]].add(step)
return len(dp[n - 1]) > 0import java.util.*;
class Solution {
public boolean canCross(int[] nums) {
int[] stones = nums;
int n = stones.length;
if (n == 1) return true;
Map<Integer,Integer> pos = new HashMap<>();
for (int i = 0; i < n; i++) pos.put(stones[i], i);
List<Set<Integer>> dp = new ArrayList<>();
for (int i = 0; i < n; i++) dp.add(new HashSet<>());
dp.get(0).add(0);
for (int i = 0; i < n; i++) {
for (int k : new ArrayList<>(dp.get(i))) {
for (int step = k - 1; step <= k + 1; step++) {
if (step > 0) {
int nxt = stones[i] + step;
Integer j = pos.get(nxt);
if (j != null) dp.get(j).add(step);
}
}
}
}
return !dp.get(n - 1).isEmpty();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool canCross(vector<int>& nums) {
vector<int>& stones = nums;
int n = stones.size();
if (n == 1) return true;
unordered_map<long long,int> pos;
for (int i = 0; i < n; i++) pos[stones[i]] = i;
vector<set<int>> dp(n);
dp[0].insert(0);
for (int i = 0; i < n; i++) {
for (int k : dp[i]) {
for (int step = k - 1; step <= k + 1; step++) {
if (step > 0) {
long long nxt = (long long)stones[i] + step;
if (pos.count(nxt)) dp[pos[nxt]].insert(step);
}
}
}
}
return !dp[n - 1].empty();
}
};/**
* @param {number[]} nums
* @return {boolean}
*/ var canCross = function(nums) {
const stones = nums, n = stones.length;
if (n === 1) return true;
const pos = {};
for (let i = 0; i < n; i++) pos[stones[i]] = i;
const dp = Array.from({length: n}, () => new Set());
dp[0].add(0);
for (let i = 0; i < n; i++) {
for (const k of dp[i]) {
for (let step = k - 1; step <= k + 1; step++) {
if (step > 0) {
const nxt = stones[i] + step;
if (pos[nxt] !== undefined) dp[pos[nxt]].add(step);
}
}
}
}
return dp[n - 1].size > 0;
};