Ctrl K

Shortest Program for a Rail Robot

Hard
A robot stands at point 0 on an endless rail, heading in the positive direction with speed +1. It may also move into negative coordinates. The robot runs a program, which is a string of two kinds of commands: - F (forward): the position grows by the current speed, then the speed doubles; - T (turn): if the speed is positive it becomes -1, otherwise it becomes +1. The position stays the same. For example, under the program FFT the robot visits positions 0 → 1 → 3 → 3 while its speed goes 1 → 2 → 4 → -1. Return the length of the shortest program that leaves the robot at point goal.
Example 1
goal=7 → 3

The program FFF: positions 0 → 1 → 3 → 7.

Example 2
goal=5 → 7

For instance FFTFTFF: 0 → 1 → 3, turn, 3 → 2, turn, 2 → 3 → 5. Nothing shorter works.

Example 3
goal=2 → 4
Constraints
  • 1 ≤ goal ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPattern With Dot and Star HardLongest Balanced Bracket Stretch HardWater Between Walls HardDoes the Text Fit the Pattern HardBiggest Solid Panel Block Hard
loading Python…
Input
goal=7
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 52 tests on the server, hidden ones included.