Robot Return to Origin
Problem
A robot starts at the origin (0, 0). Given a string of moves ('U', 'D', 'L', 'R'), return true if and only if the robot ends at (0, 0).
moves = "UD"truedef judge_circle(moves):
x = y = 0
for ch in moves:
if ch == 'U': y += 1
elif ch == 'D': y -= 1
elif ch == 'L': x -= 1
elif ch == 'R': x += 1
return x == 0 and y == 0
function judgeCircle(moves) {
let x = 0, y = 0;
for (const ch of moves) {
if (ch === 'U') y++;
else if (ch === 'D') y--;
else if (ch === 'L') x--;
else if (ch === 'R') x++;
}
return x === 0 && y === 0;
}
class Solution {
public boolean judgeCircle(String moves) {
int x = 0, y = 0;
for (char ch : moves.toCharArray()) {
if (ch == 'U') y++;
else if (ch == 'D') y--;
else if (ch == 'L') x--;
else if (ch == 'R') x++;
}
return x == 0 && y == 0;
}
}
bool judgeCircle(string moves) {
int x = 0, y = 0;
for (char ch : moves) {
if (ch == 'U') y++;
else if (ch == 'D') y--;
else if (ch == 'L') x--;
else if (ch == 'R') x++;
}
return x == 0 && y == 0;
}
Explanation
The robot returns to where it started only if its up moves cancel its down moves and its left moves cancel its right moves. So we just track its position and check if it ends back at the origin.
We keep two counters, x and y, both starting at 0. As we read each move character, 'U' does y += 1, 'D' does y -= 1, 'L' does x -= 1, and 'R' does x += 1. This is a tiny simulation of walking on a grid.
At the end we simply return whether x == 0 and y == 0. If both coordinates are back to zero, the robot landed exactly on its starting square; otherwise it ended somewhere else.
Example: moves = "UD". Start at (0, 0). 'U' moves to (0, 1), then 'D' moves back to (0, 0). Final position is the origin, so the answer is true.
We look at each move once and only keep two numbers, so this is fast and uses constant extra memory.