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 - BFS Approach INPUT 0 (Start) 3 (Target) 1 2 Car Instructions 'A': pos += speed, speed *= 2 'R': reverse speed direction Input target = 3 Start: pos=0, speed=+1 Goal: reach position 3 ALGORITHM STEPS 1 Initialize BFS Queue: [(pos=0, speed=1)] 2 Process State Try 'A' and 'R' moves 3 Explore States Track visited (pos,speed) 4 Return Distance When pos == target BFS Exploration (0,1) (1,2) A (0,-1) R FINAL RESULT Optimal Path: "AA" pos=0 speed=1 A pos=1 speed=2 A pos=3 speed=4 TARGET OK Output 2 Shortest sequence length to reach target = 3 "AA" = 2 instructions Key Insight: BFS guarantees the shortest path because it explores all states at distance d before distance d+1. State = (position, speed). Each 'A' doubles speed and moves; each 'R' reverses direction. For target=3: "AA" moves 0 --> 1 --> 3, which is optimal with just 2 instructions. TutorialsPoint - Race Car | BFS Approach
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