A car sits at position 0 on an endless number line, moving right with speed +1. It obeys two commands. A (accelerate) moves the car by its speed and then doubles the speed. R (reverse) leaves the car where it is and sets the speed to −1 if it was positive, or to +1 if it was negative.
Given a target position, return the length of the shortest command string that leaves the car exactly at target. The car may pass the target, and it may even go below 0, along the way.
Example 1
Input: target = 4 Output: 5 Why: AARRA: AA reaches 3, RR resets the speed to +1, A lands on 4
2 more examples and the constraints
Example 2
Input: target = 5 Output: 7 Why: AARARAA: 0 → 1 → 3, back to 2, then 3 → 5
Example 3
Input: target = 7 Output: 3 Why: AAA goes 0 → 1 → 3 → 7
Constraints
- 1 ≤ target ≤ 10,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- BFS over (position, speed)O(T log T)
- DP on distanceO(T log T)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for target = 10,000 | Verdict |
|---|---|---|---|
| BFS over (position, speed) | O(T log T) | Works; needs pruning | |
| DP on distance | O(T log T) | Best; small and exact |
T = target. BFS does hash work per state; the DP does a few array reads per cell.
Edge cases to test
- Target of the form 2^n − 1. 1, 3, 7, 15: just n A's, no turns.
- Target 2. AARA and ARRA both take 4 commands, and no shorter string lands on 2.
- Overshoot is not always best. For 5, stopping at 3 and backing up beats racing to 7.
- Largest target. 10,000 needs 45 commands; both approaches finish quickly.
Common mistakes
- Moving the car on
R; reverse only changes the speed. - Searching without bounds or a seen set, so the BFS never ends.
- Skipping the m = 0 plan (R twice in a row), which resets the speed without moving.
How to talk through it
- 1Clarify. Can the car pass the target or go negative? Is the answer the number of commands?
- 2Model it as a graph. States are (position, speed); BFS gives the fewest commands.
- 3Bound the search. Skip seen states and positions outside 0 to 2·target.
- 4Switch to DP on distance. After an R the speed is ±1, so the remaining trip is a smaller target.
- 5Test out loud. Run 1, 2, 3, 5 and a 2^n − 1 value like 7.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?