657. Robot Return to Origin
- String
- Simulation
TIME
O(n)
SPACE
O(1)
Intuition
Track x and y coordinates. The robot returns to origin if and only if the net displacement is zero in both directions.
Solution
- Initialize
x = 0, y = 0 - For each move:
'U'→y++'D'→y--'R'→x++'L'→x--
- Return
x == 0 && y == 0
Alternative: Count characters
- Return
count('U') == count('D') && count('L') == count('R')
Complexity
- Time: O(n), single pass through moves
- Space: O(1), only two variables
Edge Cases
- Empty moves → true (already at origin)
- All same direction → false
- Alternating UD or LR → true
Code
class Solution:
def judgeCircle(self, moves: str) -> bool:
"""
657. Robot Return to Origin
Time: O(n)
Space: O(1)
"""
x = y = 0
for m in moves:
if m == 'U':
y += 1
elif m == 'D':
y -= 1
elif m == 'R':
x += 1
else:
x -= 1
return x == 0 and y == 0/**
* 657. Robot Return to Origin
* Time: O(n)
* Space: O(1)
*/
class Solution {
public boolean judgeCircle(String moves) {
int x = 0, y = 0;
for (char m : moves.toCharArray()) {
if (m == 'U') y++;
else if (m == 'D') y--;
else if (m == 'R') x++;
else x--;
}
return x == 0 && y == 0;
}
}