A robot starts at the position (0, 0), the origin, on a 2D plane. Given the sequence of its moves, decide whether the robot ends up at (0, 0) after it completes all of them.
You are given a string moves that represents the move sequence of the robot, where moves[i] is its i-th move. Valid moves are 'R' (right), 'L' (left), 'U' (up) and 'D' (down).
Return True if the robot is back at the origin after it finishes all of its moves, and False otherwise.
Function Signature
def returns_to_origin(moves: str) -> bool:
Rules
-
The way the robot is facing is irrelevant.
'R'
always moves the robot one step right,
'L'
one step left,
'U'
one step up and
'D'
one step down.
-
Every move has the same magnitude.
-
Only the final position matters. Passing through the origin partway does not count.
Constraints
-
1 <= len(moves) <= 2 * 10^4
-
moves
contains only the characters
'U'
,
'D'
,
'L'
and
'R'
.
Examples
Input: moves = "UD"
Output: True
The robot moves up once and then down once. Both moves have the same magnitude, so it ends at the origin where it started.
Input: moves = "LL"
Output: False
The robot moves left twice and ends two steps to the left of the origin.
Input: moves = "LDRRUL"
Output: True
The string has two L and two R moves, which cancel horizontally, and one U and one D, which cancel vertically. The order of the moves does not change where the robot ends.