Frog Jump

Can a frog reach the last stone with jump-size constraints? Hash-map per-stone reachable jumps.

Hard
Time O(n^2) Space O(n^2)
LeetCode
3 min read
dp hash-set

Problem#

Stones at given positions; frog at first stone with jump size 1 initially. After a jump of size k, the next must be k-1, k, or k+1. Return true iff the last stone is reachable.

Examples#

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

Constraints#

  • 2 <= n <= 2000.

Approach#

reach[pos] = set of possible jump sizes that reach stone at pos. Initialize reach[0] = {0}. For each stone in order, for each k in its set, propagate to stones at pos + k - 1, pos + k, pos + k + 1.

Solution#

Frog Jump
class Solution {
public:
bool canCross(vector<int>& stones) {
unordered_map<int, unordered_set<int>> reach;
for (int s : stones) reach[s] = {};
reach[0].insert(0);
for (int s : stones) {
for (int k : reach[s]) {
for (int next : {k - 1, k, k + 1}) {
if (next > 0 && reach.count(s + next))
reach[s + next].insert(next);
}
}
}
return !reach[stones.back()].empty();
}
};

Editorial#

A pure 1D position DP doesn’t capture state — the jump size at each position matters. So the state is (position, last jump size). Hashing each position’s reachable jump sizes is the cleanest representation.

Complexity#

  • Time: O(n²).
  • Space: O(n²).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.