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 += speedspeed *= 2 - When you get instruction
'R', your car does the following:
If yourspeedis positive thenspeed = -1
Otherwisespeed = 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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code