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
OriginXYBalance Check: Moves = "UDLRLLRR"HorizontalL: 2 movesR: 2 movesโœ“ Net: 0VerticalU: 1 moveD: 1 moveโœ“ Net: 0Returns to Origin!Both axes balanced
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).
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
87.0K Views
Medium Frequency
~8 min Avg. Time
2.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen