657. Robot Return to Origin
UnknownView on LeetCode
Time: O(n)
Space: O(1)
Problem Overview
The robot only moves on a 2D grid.
Advertisement
Intuition
The robot only moves on a 2D grid. Track net displacement in x (L/R) and y (U/D). After all moves, the robot returns to the origin exactly when both coordinates are zero.
Algorithm
- 1Initialize x = 0, y = 0.
- 2For each character: L decrements x, R increments x, U increments y, D decrements y.
- 3Return true iff x == 0 and y == 0 after the full string.
Example Walkthrough
Input: moves = "UD"
- 1.U: y=1. D: y=0. x stays 0.
Output: true
Common Pitfalls
- •Empty moves string returns true.
- •Only final displacement matters, not visit order.
- •Input is always valid moves only.
657.cs
C#
// Approach: Count horizontal (L/R) and vertical (U/D) moves separately;
// return true only if both net displacements are zero.
// Time: O(n) Space: O(1)
public class Solution
{
public bool JudgeCircle(string moves)
{
int right = 0;
int up = 0;
foreach (char move in moves)
{
switch (move)
{
case 'R':
right++;
break;
case 'L':
right--;
break;
case 'U':
up++;
break;
case 'D':
up--;
break;
}
}
return right == 0 && up == 0;
}
}Advertisement
Was this solution helpful?