Robot Return to Origin - Problem
Imagine a robot starting its journey at the origin point (0, 0) on a 2D coordinate plane. The robot receives a sequence of movement commands and executes them one by one.
You are given a string moves where each character represents a single movement command:
'R'- Move right (increases x-coordinate by 1)'L'- Move left (decreases x-coordinate by 1)'U'- Move up (increases y-coordinate by 1)'D'- Move down (decreases y-coordinate by 1)
Your task is to determine whether the robot returns to the origin (0, 0) after executing all the movement commands.
Note: The robot's facing direction is irrelevant - each command always moves the robot in the absolute direction regardless of its current orientation.
Goal: Return true if the robot ends up at the origin, false otherwise.
Input & Output
example_1.py โ Simple Return
$
Input:
moves = "UD"
โบ
Output:
true
๐ก Note:
The robot moves up one step, then down one step. It ends up back at the origin (0,0).
example_2.py โ Square Path
$
Input:
moves = "RRULLDD"
โบ
Output:
false
๐ก Note:
Starting at origin: R(1,0) โ R(2,0) โ U(2,1) โ L(1,1) โ L(0,1) โ D(0,0) โ D(0,-1). The robot ends at (0,-1), not at origin.
example_3.py โ Balanced Movements
$
Input:
moves = "RRLLURDD"
โบ
Output:
true
๐ก Note:
R appears 2 times, L appears 2 times (balanced horizontally). U appears 1 time, D appears 2 times (not balanced vertically), so result is false. Wait, let me recount: R=2, L=2, U=1, D=2. This should be false. Let me correct: moves="RRLLURDD" has R=2, L=2, U=1, D=2, so it returns false.
Constraints
- 1 โค moves.length โค 2 ร 104
- moves consists only of the characters 'U', 'D', 'L' and 'R'
- Each move has equal magnitude (distance of 1)
Visualization
Tap to expand
Understanding the Visualization
1
Process All Moves
Count or track net displacement for each axis
2
Check Horizontal Balance
Net horizontal displacement must be zero (L = R)
3
Check Vertical Balance
Net vertical displacement must be zero (U = D)
4
Determine Result
Robot returns to origin only if both axes are balanced
Key Takeaway
๐ฏ Key Insight: A robot returns to origin if and only if the number of moves in each direction equals the number of moves in the opposite direction (L=R and U=D).
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code