Robot Return to Origin

Easy
0/40
0 upvote

Problem statement

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.


Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first and only line of input contains a single string moves.


Output Format:
Your function should return a boolean value: true if the robot returns to the origin, and false otherwise.


Note:
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.
Sample Input 1:
UD


Sample Output 1:
true


Explanation for Sample 1:
The robot starts at (0,0). It moves Up to (0,1) and then Down to (0,0). It ends at the origin.


Sample Input 2:
LL


Sample Output 2:
false


Explanation for Sample 2:
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.


Expected Time Complexity:
The expected time complexity is O(N).


Constraints:
1 <= moves.length <= 2 * 10^4
moves only contains the characters 'U', 'D', 'L', and 'R'.

Time limit: 1 sec
Approaches (1)
Time Complexity
Space Complexity
Code Solution
(100% EXP penalty)
Robot Return to Origin
Full screen
Console