A robot starts at the origin, position (0, 0), on a 2D Cartesian plane. You are given a string of moves representing a sequence of its movements.
The valid moves are:
'U' (Up): The robot's y-coordinate increases by 1.
'D' (Down): The robot's y-coordinate decreases by 1.
'R' (Right): The robot's x-coordinate increases by 1.
'L' (Left): The robot's x-coordinate decreases by 1.
Your task is to determine if the robot ends up back at the origin (0, 0) after completing all the moves in the sequence.
The first and only line of input contains a single string moves.
Your function should return a boolean value: true if the robot returns to the origin, and false otherwise.
The problem can be solved by simulating the robot's position. Alternatively, a more direct approach is to realize that the robot returns to the origin if and only if the total number of 'U' moves equals the total number of 'D' moves, AND the total number of 'L' moves equals the total number of 'R' moves.
UD
true
The robot starts at (0,0). It moves Up to (0,1) and then Down to (0,0). It ends at the origin.
LL
false
The robot starts at (0,0). It moves Left to (-1,0) and then Left again to (-2,0). It does not end at the origin.
The expected time complexity is O(N).
1 <= moves.length <= 2 * 10^4
moves only contains the characters 'U', 'D', 'L', and 'R'.
Time limit: 1 sec