Python 0818.py
class Solution:
def racecar(self, target: int) -> int:
todo = set([( 0, +1 )]) # (pos, speed)
have = set()
step = 0
while True:
next = set()
for pos, speed in todo:
if pos == target:
return step
# prune useless states
if pos > 2 * target or pos < 0:
continue
# accelerate
if target == pos + speed:
return step + 1
state = ( pos + speed, speed * 2 )
if state not in have:
next.add(state)
# brake
state = ( pos, -1 if speed > 0 else +1 )
if state not in have:
next.add(state)
step += 1
todo = next
have |= next
Difficulty
and has an acceptance rate of about 45% (200k+ submissions).
Typical patterns to solve this problem:
- Dynamic Programming
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 classic “race car” problem by performing a breadth-first search (BFS) over the state space defined by the car’s position and speed. Each iteration of the outer loop corresponds to one time step, and the algorithm expands all reachable states for that step while avoiding revisiting previously explored configurations. The search terminates as soon as the target position is reached, either directly from the current state or by an immediate acceleration.
Key Steps
Initialization of Search Structures
The algorithm starts by creating a set named todo that holds the initial state (0, +1), representing the car at the starting line with a speed of one unit per step. A second set, have, records all states that have already been processed, preventing redundant work. A counter step tracks the number of moves taken so far.
todo = set([(0, +1)]) # (position, speed)
have = set()
step = 0
Main BFS Loop
The core of the solution is an infinite loop that repeatedly expands the frontier of states. At the beginning of each iteration a fresh set next is prepared to collect the states reachable in the upcoming step.
while True:
next = set()
...
State Expansion and Goal Check
For every (pos, speed) pair in the current frontier, the algorithm first checks whether the car has already arrived at the target. If so, the current step count is returned as the answer.
for pos, speed in todo:
if pos == target:
return step
Pruning of Unproductive States
To keep the search space bounded, the code discards any state whose position is either negative or exceeds twice the target distance. This heuristic eliminates paths that have clearly overshot the goal and would require an excessive number of reversals to become useful.
if pos > 2 * target or pos < 0:
continue
Immediate Reachability via Acceleration
Before generating new states, the algorithm checks whether a single acceleration would land the car exactly on the target. This early exit saves an entire BFS layer when the solution is one step away.
if target == pos + speed:
return step + 1
Generation of the Accelerate State
When the immediate reachability test fails, the algorithm creates the state that results from applying the “accelerate” command: the position advances by the current speed and the speed doubles. The new state is added to next only if it has not been seen before.
state = (pos + speed, speed * 2)
if state not in have:
next.add(state)
Generation of the Brake (Reverse) State
The “brake” command keeps the position unchanged but flips the direction of motion and resets the speed magnitude to one. The sign of the new speed depends on the current direction: a positive speed becomes -1, while a negative speed becomes +1. As with acceleration, the state is added only if it is new.
state = (pos, -1 if speed > 0 else +1)
if state not in have:
next.add(state)
Advancement to the Next BFS Layer
After processing all states in the current frontier, the step counter is incremented, the todo set is replaced by the newly collected next set, and the have set is updated to include all states that have now been explored.
step += 1
todo = next
have |= next
Edge Cases Handled
The implementation explicitly addresses several boundary conditions:
- Target at the Starting Position - The initial check
if pos == targetcatches the case where the target is zero, returning a step count of zero without entering the expansion logic. - Immediate Arrival by Accelerating - The condition
if target == pos + speedcaptures scenarios where a single acceleration reaches the goal, allowing the function to returnstep + 1without further BFS expansion. - Overshoot Beyond Reasonable Bounds - By discarding states with
pos > 2 * targetorpos < 0, the algorithm avoids exploring paths that have moved far beyond the target or into negative territory, both of which would require additional reversals that are unlikely to be optimal. - Direction Reversal - The brake operation correctly flips the sign of the speed while resetting its magnitude, ensuring that the car can change direction from any speed without violating the problem’s rules.
Performance Optimizations
Several design choices contribute to the efficiency of the search:
- State Deduplication via Sets - Both
todoandhaveare implemented as Python sets, providing O(1) average-time membership checks. This prevents the algorithm from revisiting identical(position, speed)pairs, dramatically reducing the number of explored nodes. - Early Termination Checks - The immediate target detection after acceleration (
target == pos + speed) and the direct equality test at the start of each iteration allow the algorithm to stop as soon as the optimal solution is found, avoiding unnecessary processing of deeper BFS layers. - Bounded Exploration - The pruning condition that eliminates states outside the interval
[0, 2 * target]limits the search space to a region that is provably sufficient for finding the shortest sequence of commands. This heuristic reduces both the number of generated states and the memory footprint of thehaveset. - Incremental Frontier Replacement - By assigning
todo = nextafter each step, the algorithm discards the previous frontier entirely, freeing memory associated with states that are no longer needed for future expansions.
These mechanisms together enable the solution to explore the state space efficiently while guaranteeing that the first time the target is encountered corresponds to the minimal number of steps required.
ELI5 - Simplified Explanation
Imagine a tiny toy car on a long track and the goal is to reach a special spot marked by the number target. The car starts at the very beginning at position zero and moves forward with a speed of one. Every time the car moves, it can either go faster by doubling its speed or it can stop and turn around to head back the other way.
Because the car can make many different choices, it creates a branching path of possibilities. The code keeps track of every place the car could possibly be and how fast it could be going at each moment. It looks at all the immediate spots the car could reach in its next move and saves them to look at during the following turn. It keeps doing this turn by turn, moving outward in waves like ripples in a pond, until it finally finds the spot where the car lands exactly on the target number. This ensures that the first time the car reaches the goal, it has taken the smallest number of steps possible. It ignores any paths that go way too far past the target because those paths just take too long and are not helpful.
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++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | ||||||||
| leetcode.ca | C++ | Java | Go | Python | ||||||
| LeetcodeHelp | C++ | Java | Python | |||||||
| Progiez | C++ | Java | Python | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| gouthampradhan | Java | |||||||||
| JoshCrozier | JS | |||||||||
| martianoff | Scala | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| wisdompeak | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| gouthampradhan | Java | |||||||||
| JoshCrozier | JavaScript | |||||||||
| martianoff | Scala | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 1589: Maximum Sum Obtained of Any Permutation
- problem 2135: Count Words Obtained After Adding a Letter
- problem 1289: Minimum Falling Path Sum II
- problem 2262: Total Appeal of A String
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