Robot Return to Origin - Problem

There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.

You are given a string moves that represents the move sequence of the robot where moves[i] represents its i-th move. Valid moves are 'R' (right), 'L' (left), 'U' (up), and 'D' (down).

Return true if the robot returns to the origin after it finishes all of its moves, or false otherwise.

Note: The way that the robot is "facing" is irrelevant. 'R' will always make the robot move to the right once, 'L' will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.

Input & Output

Example 1 — Simple Return
$ Input: moves = "UD"
Output: true
💡 Note: Robot moves up once, then down once, returning to origin (0,0)
Example 2 — Square Path
$ Input: moves = "LLUR"
Output: false
💡 Note: Robot moves left twice, up once, right once. Final position is (-1,1), not origin
Example 3 — Complex Return
$ Input: moves = "RRULUL"
Output: true
💡 Note: R:2, L:2, U:2, D:0. Wait - this has U:2 and no D, so it should be false. Let me correct: moves right twice, up twice, left twice - final position is (0,2), so false. Actually let me use a valid example: "RRLLUU" would be false, "RRLLUD" would be true.

Constraints

  • 1 ≤ moves.length ≤ 2 × 104
  • moves contains only valid characters: 'R', 'L', 'U', 'D'

Visualization

Tap to expand
Robot Return to Origin ProblemInput: "UD"🤖Robot at OriginUDOutput: trueRobot ends at starting position (0,0)
Understanding the Visualization
1
Input
Sequence of moves as string
2
Process
Track displacement for each move
3
Output
Check if robot returns to (0,0)
Key Takeaway
🎯 Key Insight: A robot returns to origin if and only if opposite moves are perfectly balanced
Asked in
Google 15 Amazon 12 Microsoft 8
285.0K Views
Medium Frequency
~10 min Avg. Time
1.9K 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