A frog wants to cross a river by hopping between stones. You are given stones, the positions of the stones in increasing order. The first stone is at position 0, the frog starts there, and its first hop must be exactly 1 unit long.
After a hop of k units, the next hop must be k - 1, k or k + 1 units, always forward, and it must end on a stone. Return true if the frog can reach the last stone, and false if it cannot.
Example 1
Input: stones = [0, 1, 3, 4, 6, 9] Output: true Why: hops of 1, 2, 1, 2, 3 visit 1, 3, 4, 6, 9
2 more examples and the constraints
Example 2
Input: stones = [0, 1, 2, 3, 5, 9] Output: false Why: the frog reaches 5 with hops of 2 at most, and 9 is 4 away
Example 3
Input: stones = [0, 2] Output: false Why: the first hop must be 1, and position 1 is water
Constraints
- 2 ≤ number of stones ≤ 2,000
- 0 ≤ stones[i] ≤ 2,147,483,647 (2^31 − 1)
- stones[0] is 0, and the positions are strictly increasing
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- DFS with memoO(n²)
- Jump sets per stoneO(n²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 2,000 stones | Verdict |
|---|---|---|---|
| DFS with memo | O(n²) | Passes; deep recursion | |
| Jump sets per stone | O(n²) | Best; a plain loop |
n = number of stones.
Edge cases to test
- Second stone not at 1. [0, 2] fails at once: the first hop is always 1.
- Two stones. [0, 1] is one hop of 1: true.
- A gap too wide. Hop sizes grow by at most 1 per hop, so a gap much larger than the hops so far cannot be crossed.
- Huge positions. A position near 2^31 − 1 plus a hop overflows a 32-bit int; add in 64 bits.
Common mistakes
- Tracking only the stone, not the last jump, so different arrivals get mixed up.
- Allowing a jump of 0, or a backward jump, when k is 1 or 0.
- Plain recursion without a memo, which repeats the same (stone, jump) pairs and times out.
How to talk through it
- 1Clarify. Is the first hop always 1? Are positions sorted and distinct? Can the frog hop backward?
- 2Name the state. Where the frog can go depends on its stone and its last hop, so the state is (stone, k).
- 3Search with a memo. Try k − 1, k, k + 1 and remember pairs that fail; that is O(n²) states.
- 4Fill it forward. Keep a set of landing jumps per stone and push each one ahead; no recursion needed.
- 5Test out loud. Run [0, 2], [0, 1] and a case with a gap that is one too wide.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?