Problem 403

Abstract / Summary

A frog wants to cross a river by landing only on stones, determine if it can reach the last stone using jumps of certain lengths.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0403.py

class Solution:
    def canCross(self, stones: List[int]) -> bool:
        if 1 not in stones:
            return False

        del stones[0] # == 0

        dp = {}
        for s in stones:
            dp[s] = set()
        dp[1] = set([ 1 ])

        for s in stones:
            for k in dp[s]:
                if k > 1 and s + k - 1 in dp:
                    dp[s + k - 1].add(k - 1)
                if k > 0 and s + k     in dp:
                    dp[s + k].    add(k)
                if           s + k + 1 in dp:
                    dp[s + k + 1].add(k + 1)

        last = max(stones)
        return len(dp[last]) > 0
23 lines | 652 bytes | submitted August 27, 2023 | GitHub   5% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 47% (700k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation determines whether a frog can cross a river by jumping on a sequence of stones positioned at integer distances. The algorithm models the problem as a reachability search where each stone records the set of jump lengths that can land on it. By propagating possible jumps forward, the code ultimately checks if any jump reaches the last stone.

Initialization

The first logical block validates the minimal requirement for a successful crossing. The frog must be able to make an initial jump of length 1, therefore the presence of stone 1 is mandatory.

if 1 not in stones:
    return False

The stone at position 0 is implicit and not needed for further processing, so it is removed from the list, leaving only the positions that the frog may actually land on.

del stones[0]   # == 0

A dictionary named dp is created where each key is a stone position and the associated value is a set that will hold all jump lengths that can reach that stone. All stones are pre-populated with empty sets, establishing a uniform structure for later updates.

dp = {}
for s in stones:
    dp[s] = set()

The initial condition is then seeded: the frog can reach stone 1 with a jump of length 1, so the set for stone 1 receives the value 1.

dp[1] = set([1])

Dynamic Programming Loop

The core of the algorithm iterates over each stone in ascending order. For every stone s, it examines each jump length k that is known to land on s. From that state, three possible next jumps are considered: k-1, k, and k+1. Each candidate jump is only applied if it yields a positive length (except for the k+1 case, which is always positive) and if the target position exists in the dp dictionary, meaning there is a stone at that location.

for s in stones:
    for k in dp[s]:
        if k > 1 and s + k - 1 in dp:
            dp[s + k - 1].add(k - 1)
        if k > 0 and s + k in dp:
            dp[s + k].add(k)
        if s + k + 1 in dp:
            dp[s + k + 1].add(k + 1)

The three conditional branches handle the three permissible jump adjustments:

  • When k > 1, a shorter jump of k-1 is possible, and the code adds this new length to the set of the stone located at s + k - 1.
  • When k > 0, the same length k is retained, and the target stone at s + k receives this length.
  • The longest allowed jump, k + 1, is always considered; if a stone exists at s + k + 1, the new length is recorded.

By storing only the lengths that actually lead to a stone, the algorithm avoids exploring unreachable positions, effectively pruning the search space.

Final Check

After all reachable states have been propagated, the algorithm identifies the farthest stone, which is the maximum value in the original stones list. The presence of any jump length in the set associated with this stone indicates that the frog can land on the final position, and the function returns True. If the set is empty, no sequence of jumps reaches the end, and False is returned.

last = max(stones)
return len(dp[last]) > 0

Edge Cases Handled

The code explicitly handles the scenario where the second stone (position 1) is missing, immediately returning False because the frog cannot make the required first jump. By deleting the initial stone at position 0, the algorithm ensures that subsequent calculations treat the list as a pure collection of reachable positions, eliminating any accidental reference to the starting point.

The conditional checks k > 1 and k > 0 prevent the generation of non-positive jump lengths, which would be invalid in the problem domain. The existence test s + … in dp guarantees that only jumps landing on actual stones are recorded, thereby ignoring any hypothetical positions that are not part of the input.

Performance Optimizations

The use of a dictionary mapping stone positions to sets provides constant-time lookup for both the existence of a target stone and the insertion of a new jump length. This eliminates the need for linear scans over the stone list during each transition. By iterating over the stones in their natural order and only processing jump lengths that have already been proven reachable, the algorithm avoids redundant work and keeps the number of examined states proportional to the number of feasible jump combinations rather than the square of the number of stones.

Storing jump lengths as a set automatically deduplicates identical lengths that may be discovered via different paths, preventing unnecessary repeated processing of the same state. This set-based aggregation contributes to a leaner memory footprint and reduces the number of inner-loop iterations.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a little frog trying to hop across a river by jumping on flat stones. The stones are lined up at different distances from the start, and the frog needs to follow special rules for how far it can jump.

Every time the frog lands on a stone, it remembers the length of the jump that brought it there. The frog can jump again by taking the same distance it just used, one step further, or one step less.

The code sets up a list to keep track of every stone in the river. It starts by making sure the frog can jump to the very first stone. After that, the computer looks at each stone one by one. For every stone the frog reaches, the computer checks all the possible next jumps the frog could make to land on another stone further down the path.

Think of this like a map where the computer writes down every way the frog could possibly reach each stone. If the frog can successfully jump from stone to stone until it reaches the final stone at the end of the river, then the puzzle is solved. The computer keeps track of all these possibilities until it sees if the last stone has at least one way to be reached.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.96 | σ = 1.67

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Rust Python Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
chenyanzhe C++
everthis JS
haoel C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
MacJim C++
ruoru Rust
suxrobGM C#
varunu28 Java
vli02 C
wisdompeak C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
MacJim C++
ruoru Rust
suxrobGM C#
varunu28 Java
vli02 C
wisdompeak C++
zfang399 C++
35 links | 21 authors | 9 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

2 hard
3 solutions   August 27, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality