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 = "RRLLUD"
Output: true
💡 Note: Robot moves right twice, left twice, up once, down once. R and L cancel out, U and D cancel out, returning to origin (0,0)

Constraints

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

Visualization

Tap to expand
Robot Return to Origin Balance Tracking Approach INPUT Robot starts at origin (0,0) X Y R (0,0) R+ L- U+ D- Move Sequence: U D moves = "UD" Up then Down ALGORITHM STEPS 1 Initialize Counters x = 0, y = 0 2 Process 'U' move y++ --> y = 1 3 Process 'D' move y-- --> y = 0 4 Check Position x == 0 AND y == 0? Move x y init 0 0 U 0 1 D 0 0 FINAL RESULT U D R Back at (0,0) Final Position x=0, y=0 Output: true Robot returned! OK Origin Reached! Key Insight: Track x and y coordinates separately. R/L affect x (+1/-1), U/D affect y (+1/-1). Robot returns to origin only when BOTH x=0 AND y=0. Each direction must be balanced! Time: O(n) | Space: O(1) - only two counters needed regardless of input size. TutorialsPoint - Robot Return to Origin | Balance Tracking Approach
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