Problem 818

Abstract / Summary

A car must reach a target position using accelerate and reverse actions with minimal commands.

Note

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

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
32 lines | 904 bytes | submitted March 1, 2024 | GitHub   17% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 45% (200k+ submissions).

Typical patterns to solve this problem:
  • 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 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 == target catches 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 + speed captures scenarios where a single acceleration reaches the goal, allowing the function to return step + 1 without further BFS expansion.
  • Overshoot Beyond Reasonable Bounds - By discarding states with pos > 2 * target or pos < 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 todo and have are 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 the have set.
  • Incremental Frontier Replacement - By assigning todo = next after 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.

written by openai gpt

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.

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 = 7 | μ = 6.48 | σ = 1.71

Complexity Analysis

not analyzed yet

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
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++
26 links | 15 authors | 9 languages

Videos

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

Solved On The Same Day

5 solutions   March 1, 2024

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