Race Car - Problem

Your car starts at position 0 and speed +1 on an infinite number line. Your car can go into negative positions.

Your car drives automatically according to a sequence of instructions 'A' (accelerate) and 'R' (reverse):

  • When you get instruction 'A', your car does the following:
    position += speed
    speed *= 2
  • When you get instruction 'R', your car does the following:
    If your speed is positive then speed = -1
    Otherwise speed = 1
    Your position stays the same.

For example, after commands "AAR", your car goes to positions 0 → 1 → 3 → 3, and your speed goes to 1 → 2 → 4 → -1.

Given a target position target, return the length of the shortest sequence of instructions to get there.

Input & Output

Example 1 — Target at 3
$ Input: target = 3
Output: 2
💡 Note: Start at position 0, speed 1. First 'A': position becomes 0+1=1, speed becomes 1×2=2. Second 'A': position becomes 1+2=3, speed becomes 2×2=4. We reach target 3 in 2 steps: "AA"
Example 2 — Target at 6
$ Input: target = 6
Output: 5
💡 Note: Optimal sequence is "AAARA": A(1,2) → A(3,4) → A(7,8) → R(7,-1) → A(6,2). This takes 5 steps to reach target 6
Example 3 — Target at 1
$ Input: target = 1
Output: 1
💡 Note: Just one 'A' instruction: position becomes 0+1=1, which is the target. Only 1 step needed

Constraints

  • 1 ≤ target ≤ 104

Visualization

Tap to expand
Race Car Problem: Reach Target with Minimum InstructionsNumber Line0START3TARGETInstruction Aposition += speedspeed *= 2Instruction Rspeed = speed > 0? -1 : 1Find Shortest PathMinimum sequence: AA (2 steps)Example: Start(0,speed=1) → A(1,speed=2) → A(3,speed=4) = Target!
Understanding the Visualization
1
Start
Car at position 0, speed 1
2
Instructions
A: move forward and double speed, R: reverse direction
3
Goal
Find shortest sequence to reach target
Key Takeaway
🎯 Key Insight: Model as shortest path problem where BFS guarantees minimum steps to target
Asked in
Google 45 Facebook 30 Amazon 25
28.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen