All problems
1167HardDynamic ProgrammingHeuristic SearchA* Search

Driving the Trolley to the Mark

Tracked in this browser only
Write code

Trains the technique from

LeetCode 818Race Car

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A trolley stands at position 0 on a rail, facing forwards with a speed of 1.

Two controls are available:

  • Push moves the trolley forward by its speed, then doubles that speed. Facing backwards the speed is negative, so the trolley moves backwards and the speed doubles in size.
  • Turn sets the speed to 1 when it was negative and to -1 when it was positive. The trolley does not move.

Return the fewest presses needed to bring the trolley to position target.

Examples

Example 1

Input
target = 1
Output
1

One push carries the trolley one place and it has arrived.

Example 2

Input
target = 7
Output
3

Three pushes carry the trolley 1, then 2, then 4 places, which is exactly seven.

Example 3

Input
target = 4
Output
5

Push twice to reach 3, then turn twice to bring the speed back to one without moving, and push once more to land on 4. A third push would have overshot to 7.

Constraints

  • 1 <= target <= 10^4

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def racecar(target: int) -> int:
Java
public int racecar(int target)
September 7
Apply