All problems
0684MediumTwo PointersString

Shunting Trolleys Along a Siding

Tracked in this browser only
Write code

Trains the technique from

LeetCode 2337Move Pieces to Obtain a String

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 single-track siding is written as a string, one character per bay:

  • '<' is a trolley whose brake lets it be pushed only towards the left end;
  • '>' is a trolley whose brake lets it be pushed only towards the right end;
  • '.' is an empty bay.

One push moves a single trolley one bay in its allowed direction. A push is legal only when the destination bay lies on the siding and is empty, so a trolley can never be pushed off an end of the siding and can never be pushed onto an occupied bay.

You are given the current layout start and a wanted layout goal, both of the same length. Return true if some sequence of legal pushes turns start into goal, and false otherwise. Zero pushes is a valid sequence.

Examples

Example 1

Input
start = ".<..>", goal = "<...>"
Output
true

One push takes the `'<'` from bay 1 into the empty bay 0, which is its allowed direction. The `'>'` already sits where the goal wants it.

Example 2

Input
start = "<.>", goal = "<>."
Output
false

The goal asks the `'>'` to end up in bay 1, which is to the left of the bay 2 it starts in, and a `'>'` can only be pushed rightwards.

Example 3

Input
start = "<.", goal = "<<"
Output
false

The goal shows two trolleys while the siding holds one, and a push never adds a trolley.

Constraints

  • 1 <= start.length <= 10^5
  • start.length == goal.length
  • start and goal contain only the characters '<', '>' and '.'.

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 can_shunt(start: str, goal: str) -> bool:
Java
public boolean canShunt(String start, String goal)
September 7
Apply