Frog Jump

Hard

Topics
ArrayDynamic ProgrammingHash Table

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

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

Example 2

00112233448596117
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

  1. Build pos, a map from stone position to its index.
  2. dp[i] is the set of jump sizes that can land on stone i. Seed dp[0] = {0} — the frog starts on stone 0 having jumped nothing. The first jump must therefore be 0+1 = 1, which matches the rule that the first jump is always 1.
  3. Sweep stones left to right. For each arriving jump size k, try k-1, k, k+1; for each positive step landing on an existing stone, add that step to the target's set.
  4. 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 -> true

Stone 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 dp is 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-1 must 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]) > 0
Asked at PhonePe Snap Sprinklr
SensAI
Beta
Tap the mic to stop voice mode