Frog Jump (LeetCode 403): Solution and Explanation
A frog crosses a river by hopping between stones at given sorted positions. Its first jump is exactly one unit, and if its last jump was k units, the next must be k - 1, k or k + 1 units forward. Decide whether it can land on the last stone.
Watch it run step by step
Try your own input and write the code →Intuition
The frog's options at any moment depend on two things: which stone it stands on and how long its previous jump was. Position alone is not enough, since reaching stone 8 with a jump of 2 allows different moves than reaching it with a jump of 3. A plain recursive search over all jump sequences branches three ways at every step and repeats the same (stone, jump) situations many times, which blows up exponentially.
Once we see that the state is the pair (stone, last jump), the duplication is easy to remove. For each stone, keep the set of jump sizes that can arrive there. Because stones are sorted and the frog only moves forward, we can process stones left to right: by the time we reach a stone, every jump that could land on it has already been recorded by an earlier stone.
From each stone and each arriving jump size k, try the three next sizes k - 1, k and k + 1. If the target position is a stone, add that size to the target's set, and if the target is the last stone we are done. Each stone can hold at most O(n) distinct jump sizes, because a jump can never be longer than the number of jumps made so far plus one, so the total work is quadratic rather than exponential. A quick early exit also helps: if the second stone is not at position 1, the mandatory first jump lands in water.
Approach: DP map from stone to arriving jump sizes
- If
stones[1] != 1, return false, since the first jump must be exactly 1. - Build
stone_setfor O(1) position lookups. If the last stone is 1, return true. - Create
dpmapping each stone to an empty set and add jump size 1 todp[1]. - Process stones from the second one onward, and for each jump size
kindp[stone], trynext_kink - 1,k,k + 1. - Skip non-positive sizes. If
stone + next_kis a stone, return true when it is the last stone, otherwise addnext_kto its set. - If the loop ends without reaching the last stone, return false.
Step-by-step example
stones = [0, 1, 3, 5, 6, 8, 12, 17]
dp[1] = {1}. From stone 1 with k = 1, a jump of 2 lands on 3, sodp[3] = {2}.- From stone 3 with k = 2, jumps of 2 and 3 land on 5 and 6, so
dp[5] = {2}anddp[6] = {3}. - From stone 5 with k = 2, a jump of 1 reaches 6 and a jump of 3 reaches 8, so
dp[6] = {1, 3}anddp[8] = {3}. - From stone 6, k = 3 allows a jump of 2 to 8, so
dp[8] = {2, 3}. Nothing else from 6 lands on a stone. - From stone 8, k = 3 allows a jump of 4 to 12, so
dp[12] = {4}. - From stone 12 with k = 4, a jump of 5 lands on 17, the last stone, so the answer is true.
Code: Python, Java, C++
1class Solution:
2 def canCross(self, stones: List[int]) -> bool:
3 if stones[1] != 1:
4 return False
5
6 stone_set = set(stones)
7 last_stone = stones[-1]
8 if last_stone == 1:
9 return True
10
11 # dp[pos] = set of possible jump sizes to reach pos
12 dp = {stone: set() for stone in stones}
13 dp[1].add(1)
14
15 for stone in stones[1:]:
16 for k in dp[stone]:
17 for next_k in [k - 1, k, k + 1]:
18 if next_k > 0 and stone + next_k in stone_set:
19 if stone + next_k == last_stone:
20 return True
21 dp[stone + next_k].add(next_k)
22
23 return False1class Solution {
2 public boolean canCross(int[] stones) {
3 if (stones[1] != 1) return false;
4
5 Set<Integer> stoneSet = new HashSet<>();
6 for (int s : stones) stoneSet.add(s);
7 int lastStone = stones[stones.length - 1];
8 if (lastStone == 1) return true;
9
10 Map<Integer, Set<Integer>> dp = new HashMap<>();
11 for (int stone : stones) dp.put(stone, new HashSet<>());
12 dp.get(1).add(1);
13
14 for (int i = 1; i < stones.length; i++) {
15 int stone = stones[i];
16 for (int k : dp.get(stone)) {
17 for (int nextK : new int[]{k - 1, k, k + 1}) {
18 if (nextK > 0 && stoneSet.contains(stone + nextK)) {
19 if (stone + nextK == lastStone) return true;
20 dp.get(stone + nextK).add(nextK);
21 }
22 }
23 }
24 }
25
26 return false;
27 }
28}1class Solution {
2public:
3 bool canCross(vector<int>& stones) {
4 if (stones[1] != 1) return false;
5
6 unordered_set<int> stoneSet(stones.begin(), stones.end());
7 int lastStone = stones.back();
8 if (lastStone == 1) return true;
9
10 unordered_map<int, unordered_set<int>> dp;
11 for (int stone : stones) dp[stone] = {};
12 dp[1].insert(1);
13
14 for (int i = 1; i < stones.size(); i++) {
15 int stone = stones[i];
16 for (int k : dp[stone]) {
17 for (int nextK : {k - 1, k, k + 1}) {
18 if (nextK > 0 && stoneSet.count(stone + nextK)) {
19 if (stone + nextK == lastStone) return true;
20 dp[stone + nextK].insert(nextK);
21 }
22 }
23 }
24 }
25
26 return false;
27 }
28};Time and space complexity
O(n²)
Each of the n stones can hold up to O(n) distinct jump sizes, and each size tries three moves with O(1) set lookups.
O(n²)
The sets of jump sizes across all stones can hold O(n²) entries in total.
Other approaches
DFS with memoization on (index, jump) (time O(n²), space O(n²))
Recursively try the three next jumps from each state and cache whether a (stone index, last jump) pair can reach the end. It explores only states that matter for the answer and can exit early, with the same worst case as the bottom-up map.
Common mistakes
- Tracking only reachable stones and not the jump size used, which loses the information that limits the next jump.
- Allowing a jump of size 0, which would let the frog stay in place forever. Only positive sizes are valid.
- Forgetting that the first jump must be exactly 1, so
stones[1]must equal 1. - Searching the stones list linearly for each landing position instead of using a set, which adds another factor of n.
Frequently asked questions
Why does Frog Jump need the last jump size in its state?
The allowed next jumps are determined by the previous one. Two paths that reach the same stone with different jump sizes have different futures, so the state must include both.
Why is the number of jump sizes per stone bounded by n?
Each jump can be at most one unit longer than the previous one, and the first is 1, so after j jumps the size is at most j + 1. The frog makes fewer than n jumps, so sizes are below n.
BFS, DFS or DP for Frog Jump?
All three work on the same (stone, jump) state graph. The forward DP over sorted stones is the simplest to write, while memoized DFS can stop as soon as it finds one successful path.