Race Car - Problem
Race Car Control Challenge
You have an autonomous race car positioned at the starting line (position 0) on an infinite racing track. The car begins with an initial speed of +1 and can move in either direction along the track.
Your car responds to two types of commands:
Example: Commands
• Start: position=0, speed=1
• After 'A': position=1, speed=2
• After 'A': position=3, speed=4
• After 'R': position=3, speed=-1
Your goal: Find the minimum number of commands needed to reach the target position exactly.
You have an autonomous race car positioned at the starting line (position 0) on an infinite racing track. The car begins with an initial speed of +1 and can move in either direction along the track.
Your car responds to two types of commands:
'A'(Accelerate): The car moves forward by its current speed, then doubles its speed
• position += speed
• speed *= 2'R'(Reverse): The car changes direction without moving
• If speed > 0, then speed = -1
• If speed < 0, then speed = 1
• Position remains unchanged
Example: Commands
"AAR" produce:• Start: position=0, speed=1
• After 'A': position=1, speed=2
• After 'A': position=3, speed=4
• After 'R': position=3, speed=-1
Your goal: Find the minimum number of commands needed to reach the target position exactly.
Input & Output
example_1.py — Basic Target
$
Input:
target = 3
›
Output:
2
💡 Note:
The shortest sequence is "AA": Start (0,1) → A (1,2) → A (3,4). We reach position 3 in 2 steps.
example_2.py — Requires Reverse
$
Input:
target = 6
›
Output:
5
💡 Note:
The optimal sequence is "AAARA": (0,1) → A (1,2) → A (3,4) → A (7,8) → R (7,-1) → A (6,2). Total: 5 steps.
example_3.py — Single Step
$
Input:
target = 1
›
Output:
1
💡 Note:
Simply accelerate once: "A" takes us from (0,1) to (1,2). We reach target 1 in just 1 step.
Constraints
- 1 ≤ target ≤ 104
- The target position is always reachable
- Speed doubles with each acceleration
- Position can be negative during the process
Visualization
Tap to expand
Understanding the Visualization
1
Initial State
Car starts at position 0 with speed +1
2
Decision Point
At each state, choose between Accelerate or Reverse
3
Accelerate Effect
Move forward by current speed, then double the speed
4
Reverse Effect
Change direction (speed becomes ±1), position unchanged
5
BFS Exploration
Explore all states level by level until target is reached
Key Takeaway
🎯 Key Insight: BFS guarantees finding the minimum steps because it explores states level by level. The first time we reach the target position is guaranteed to be via the shortest path!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code