Python 1654.py
class Solution:
def minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int:
# the sign encodes the direction of the most recent jump:
# plus means forward, minus means backward
seen = set()
for f in forbidden: # ignore forbidden positions, both signs
seen.add(+f)
seen.add(-f)
todo = set([ 0 ])
jump = 0
while todo:
next = set()
for t in todo:
# avoid processing twice
if t in seen:
continue
seen.add(t)
# separate sign and position
pos = abs(t)
back = t < 0
# done ?
if pos == x:
return jump
# next step
if pos < 10000: # avoid jumping too far right (for performance reasons)
next.add(pos + a)
if pos > b and not back:
next.add(-(pos - b))
jump += 1
todo = next
return -1
Difficulty
and has an acceptance rate of about 31% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Breadth First Search
- Hash Table
AI Disclaimer
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.
Code Walkthrough
Overview
The provided implementation solves the “minimum jumps” problem using a breadth-first search (BFS) over a state space that encodes both position and the direction of the most recent jump. Each state is represented by an integer whose sign indicates whether the last move was a backward jump (negative) or a forward jump (positive). The algorithm expands reachable states level by level until the target position x is found or all possibilities are exhausted.
Initialization of Forbidden Positions
The algorithm begins by constructing a set called seen that contains every forbidden location in both signed forms. By inserting both +f and -f for each forbidden value f, the search can later treat a forbidden position as already visited regardless of the direction from which it would be approached.
seen = set()
for f in forbidden: # ignore forbidden positions, both signs
seen.add(+f)
seen.add(-f)
This pre-population prevents any future expansion from landing on a forbidden coordinate, effectively pruning invalid branches early.
Starting State and BFS Loop
The search starts from the origin, represented by the unsigned integer 0. The variable todo holds the frontier of states to be processed at the current BFS depth, while jump counts how many jumps have been taken so far.
todo = set([0])
jump = 0
while todo:
next = set()
...
jump += 1
todo = next
The loop continues until there are no more states to explore, at which point the function returns -1 to indicate that the target cannot be reached.
Processing Each State
Inside the loop, each candidate state t from todo is examined. The algorithm first checks whether the state has already been visited by consulting seen. If it has, the state is skipped; otherwise it is added to seen to avoid future duplication.
for t in todo:
if t in seen:
continue
seen.add(t)
The absolute value of t yields the actual position on the number line, while the sign determines whether the previous jump was backward.
pos = abs(t)
back = t < 0
If the current position matches the target x, the function immediately returns the current jump count.
if pos == x:
return jump
Generation of Next Positions
Two possible moves are considered from each state:
- A forward jump of length
ais always allowed provided the resulting position does not exceed a hard-coded bound of10000. This bound limits the search space on the right side of the line, preventing the algorithm from exploring arbitrarily large positions that cannot contribute to an optimal solution.
if pos < 10000: # avoid jumping too far right (for performance reasons)
next.add(pos + a)
- A backward jump of length
bis permitted only when the current position is greater thanb(to stay non-negative) and the previous move was not already a backward jump. The sign of the new state is set to negative to record that the most recent jump was backward.
if pos > b and not back:
next.add(-(pos - b))
These conditions enforce the problem’s rule that two consecutive backward jumps are forbidden and that the frog cannot move left of the origin.
Edge Cases Handled
The code explicitly addresses several edge conditions:
-
Forbidden positions are excluded in both forward and backward contexts by storing both signed variants in
seen. This ensures that a state cannot be revisited simply by changing direction. -
The check
pos > bguarantees that a backward jump never produces a negative coordinate, respecting the constraint that the frog cannot go below zero. -
The flag
not backprevents the generation of a backward jump immediately after another backward jump, thereby satisfying the “no two backward jumps in a row” rule. -
The early termination condition
if pos == xallows the algorithm to stop as soon as the target is reached, even if other states remain in the current frontier. -
The bound
pos < 10000serves as a safeguard against infinite expansion to the right, which could otherwise occur if the forward jump lengthais large and the target is unreachable.
Performance Optimizations
Several design choices contribute to efficient execution:
-
Using a set for
todoandnextprovides O(1) average-time membership checks and eliminates duplicate states within the same BFS level. -
The
seenset doubles as both a record of visited states and a repository of forbidden positions, reducing the need for separate data structures. -
By encoding direction in the sign of the integer, the algorithm avoids storing a tuple
(position, direction). This compact representation reduces memory overhead and simplifies set operations. -
The right-hand bound (
pos < 10000) dramatically cuts down the number of forward expansions, especially in cases whereais small and the search could otherwise wander far beyond any plausible solution. -
Skipping already-seen states at the start of each iteration prevents unnecessary processing of states that have been generated earlier in the search, ensuring that each unique state is examined at most once.
Through these mechanisms, the function explores the reachable state space efficiently while adhering to the problem’s constraints.
ELI5 - Simplified Explanation
Imagine a little grasshopper that wants to reach a specific flower in a big garden. The grasshopper needs to follow special rules to move around. Some spots in the garden are forbidden, so the grasshopper must jump over them or avoid them completely. The grasshopper can jump forward by a certain distance or backward by another distance, but it cannot jump backward twice in a row.
To keep track of where the grasshopper has been, there is a magical list that remembers every spot visited. If the grasshopper lands on a spot it has already seen, it simply stops thinking about that path.
The process starts at the beginning of the garden. In each round of jumping, the grasshopper looks at all the spots it can reach next. It checks if any of those spots are the flower it is looking for. If it finds the flower, the mission is complete. If it does not, the grasshopper prepares for the next round of jumps. It only jumps forward if it stays within the boundaries of the garden, and it only jumps backward if it did not just jump backward before. This continues until the grasshopper finds the goal or runs out of new places to safely land.
Code Quality
Complexity Analysis
Other Solutions
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++ | Python | Java | TS | |||
| WalkCCC | C++ | Python | Java | |||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 2368: Reachable Nodes With Restrictions
- problem 2770: Maximum Number of Jumps to Reach the Last Index
Solved On The Same Day
- problem 1462: Course Schedule IV
- problem 1497: Check If Array Pairs Are Divisible by k
- problem 1574: Shortest Subarray to be Removed to Make Array Sorted
- problem 1590: Make Sum Divisible by P
- problem 1733: Minimum Number of People to Teach
- problem 1750: Minimum Length of String After Deleting Similar Ends
Extra
- 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