1257. Shortest Round Trip Segment

Medium3.5 points estimatedHash TablePrefix SumString3 hints

A delivery robot starts at the origin of a city grid and follows the string moves, one character per step: U moves y up by 1, D moves y down by 1, L moves x left by 1 and R moves x right by 1. A round-trip segment is a non-empty contiguous run of moves after which the robot stands exactly where it stood just before that run began.

Return the length of the shortest round-trip segment, or -1 if the string contains none. Checking every segment is O(n^2) work per pass; aim for O(n) expected time and O(n) space instead: the segment between two prefix indices is a round trip exactly when the robot stood at the same cell after both, so keep a hash map from each cell to the latest prefix index at which it was reached.

Example 1

Input:
moves = "RRUDLLL"
Output:
2
Explanation:

After RR the robot is at (2, 0); the next U and D bring it back to (2, 0), so the segment UD of length 2 is a round trip, and a single move can never be one.

Example 2

Input:
moves = "UUU"
Output:
-1
Explanation:

The robot only moves upward, so no non-empty segment returns to its start and the answer is -1.

Example 3

Input:
moves = "URDL"
Output:
4
Explanation:

The whole string traces a square and returns to the start, and no shorter segment does, so the answer is 4.

Constraints

1 ≤ moves.length ≤ 2000; moves consists only of the characters U, D, L and R.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…