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 an instruction 'A', your car does the following:
position += speed
speed *= 2
When you get an 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.
Example 1:
Input: target = 3
Output: 2
Explanation:
The shortest instruction sequence is "AA".
Your position goes from 0 --> 1 --> 3.
Example 2:
Input: target = 6
Output: 5
Explanation:
The shortest instruction sequence is "AAARA".
Your position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6.
Problem summary: 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 an instruction 'A', your car does the following: position += speed speed *= 2 When you get an 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.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming
Example 1
3
Example 2
6
Step 02
Core Insight
What unlocks the optimal approach
No official hints in dataset. Start from constraints and look for a monotonic or reusable state.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #818: Race Car
class Solution {
public int racecar(int target) {
int[] dp = new int[target + 1];
for (int i = 1; i <= target; ++i) {
int k = 32 - Integer.numberOfLeadingZeros(i);
if (i == (1 << k) - 1) {
dp[i] = k;
continue;
}
dp[i] = dp[(1 << k) - 1 - i] + k + 1;
for (int j = 0; j < k; ++j) {
dp[i] = Math.min(dp[i], dp[i - (1 << (k - 1)) + (1 << j)] + k - 1 + j + 2);
}
}
return dp[target];
}
}
// Accepted solution for LeetCode #818: Race Car
func racecar(target int) int {
dp := make([]int, target+1)
for i := 1; i <= target; i++ {
k := bits.Len(uint(i))
if i == (1<<k)-1 {
dp[i] = k
continue
}
dp[i] = dp[(1<<k)-1-i] + k + 1
for j := 0; j < k; j++ {
dp[i] = min(dp[i], dp[i-(1<<(k-1))+(1<<j)]+k-1+j+2)
}
}
return dp[target]
}
# Accepted solution for LeetCode #818: Race Car
class Solution:
def racecar(self, target: int) -> int:
dp = [0] * (target + 1)
for i in range(1, target + 1):
k = i.bit_length()
if i == 2**k - 1:
dp[i] = k
continue
dp[i] = dp[2**k - 1 - i] + k + 1
for j in range(k - 1):
dp[i] = min(dp[i], dp[i - (2 ** (k - 1) - 2**j)] + k - 1 + j + 2)
return dp[target]
// Accepted solution for LeetCode #818: Race Car
struct Solution;
use std::collections::HashMap;
use std::collections::VecDeque;
impl Solution {
fn racecar(target: i32) -> i32 {
let mut queue: VecDeque<(usize, i32, i32)> = VecDeque::new();
let mut states: HashMap<(i32, i32), usize> = HashMap::new();
queue.push_back((0, 0, 1));
states.insert((0, 1), 0);
while let Some((length, position, speed)) = queue.pop_front() {
if position == target {
return length as i32;
}
for (p, s) in Self::next(position, speed) {
if p > target + target / 3 || p < -target / 3 {
continue;
}
if states.contains_key(&(p, s)) && states[&(p, s)] <= length + 1 {
continue;
}
*states.entry((p, s)).or_default() = length + 1;
queue.push_back((length + 1, p, s));
}
}
0
}
fn next(position: i32, speed: i32) -> Vec<(i32, i32)> {
vec![
(position + speed, speed * 2),
(position, if speed > 0 { -1 } else { 1 }),
]
}
}
#[test]
fn test() {
let target = 3;
let res = 2;
assert_eq!(Solution::racecar(target), res);
let target = 6;
let res = 5;
assert_eq!(Solution::racecar(target), res);
}
// Accepted solution for LeetCode #818: Race Car
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #818: Race Car
// class Solution {
// public int racecar(int target) {
// int[] dp = new int[target + 1];
// for (int i = 1; i <= target; ++i) {
// int k = 32 - Integer.numberOfLeadingZeros(i);
// if (i == (1 << k) - 1) {
// dp[i] = k;
// continue;
// }
// dp[i] = dp[(1 << k) - 1 - i] + k + 1;
// for (int j = 0; j < k; ++j) {
// dp[i] = Math.min(dp[i], dp[i - (1 << (k - 1)) + (1 << j)] + k - 1 + j + 2);
// }
// }
// return dp[target];
// }
// }
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n × m)
Space
O(n × m)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.