Shortest Accelerate and Reverse Program for a Self-Driving Test Car
Last updated: November 29, 2026
Quick Overview
A test car starts at position 0 with speed +1 on an infinite straight track. Instruction A moves it by its speed and doubles the speed; instruction R reverses direction by setting speed to -1 if positive or +1 if negative, without moving. Return the length of the shortest instruction sequence that stops the car exactly at target.
0
0
0 solved
A test car starts at position 0 with speed +1 on an infinite straight track. Instruction A moves it by its speed and doubles the speed; instruction R reverses direction by setting speed to -1 if positive or +1 if negative, without moving. Return the length of the shortest instruction sequence that stops the car exactly at target.
A Google onsite question that combines simulation with shortest path over states. Interviewers first expect a BFS over (position, speed) with a justified pruning bound, then often ask for the dynamic programming solution that reasons about overshooting and backing up.
What the Interviewer Expects
- Model the state as (position, speed)
- Run BFS since every instruction costs one
- Prune positions outside a safe bound such as (-target, 2 * target)
- Explain why the pruning cannot discard optimal paths
- Mention the O(target log target) DP as the faster alternative
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- Derive the DP recurrence based on k = bit length of target.
- What if R also costs two units because the car must stop?
- How would you print the actual instruction sequence?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: positive integer target (up to about 10^4). Output: minimum number of A and R instructions so that the car's position equals target at the end (speed does not matter)....
High-Level Design
BFS from (0, 1). From (p, s): A gives (p + s, 2s); R gives (p, -1 if s > 0 else 1). Each costs one, so the first time we reach position target is optimal. Without bounds the state space is inf...