Robot Return to Origin solution and explanation
9 more videos on this problem
Robot Return to Origin | Simple Explanation | Leetcode 657 | codestorywithMIKcodestorywithMIK · 3:43 · 3K views
Amazon Coding Interview: Robot Return to Origin (LeetCode)Matt Upham | Tech + Coding · 6:12 · 1K views
Robot Return to Origin - LeetCode 657 - JavaScriptAlgoJS · 3:01 · 1K views
657. Robot Return to Origin | LEETCODE SOLUTION | EASYcode Explainer · 4:31 · 657 views
Amazon Interview Question | LeetCode 657. Robot Return to Origin | English | code iocode io - English · 11:42 · 526 views
Leetcode 657 | Robot Return to Origin | 2D Movement (Java Solution)The Tech Granth · 4:27 · 365 views
657. Robot Return to Origin | Leetcode Daily - PythonLeetcode Daily · 4:35 · 340 views
How to Solve "657 Robot Return to Origin" on LeetCode? - JavascriptBecoming A Better Dev (with David) · 5:19 · 128 views
Robot Return to Origin | LeetCode 657 - Pythonimpoldev · 4:29 · 107 views
Leetcode Solution - 657 Robot Return to OriginJohn Leonardo · 3:03 · 93 views
The problem
There is a robot starting at the 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 ith 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.
Example 1:
Input: moves = "UD" Output: true Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.
Example 2:
Input: moves = "LL" Output: false Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.
Constraints:
1 <= moves.length <= 2 * 104movesonly contains the characters'U','D','L'and'R'.
Approach overview
Problem Overview: You receive a string of moves where each character represents a step taken by a robot on a 2D grid: U, D, L, and R. The robot starts at coordinate (0,0). The task is to determine whether the sequence of moves brings the robot back to the origin after executing all steps.
Approach 1: Balancing Moves (O(n) time, O(1) space)
This approach simulates the robot’s movement directly. Initialize two integers x and y to represent the current coordinates. Iterate through the move string once. For each character, update the coordinates: U increments y, D decrements y, R increments x, and L decrements x. After processing all characters, check whether both coordinates returned to zero.
The key insight is that every movement changes exactly one axis by one unit. Tracking coordinates directly mirrors how the robot moves in a real grid. This solution works well for problems involving step‑by‑step movement simulation and is a common pattern in simulation problems. The algorithm performs a single pass over the input string, so the time complexity is O(n), and it uses only two integer variables, resulting in O(1) space.
Approach 2: Net Balance Using Counts (O(n) time, O(1) space)
This approach relies on the observation that opposite moves cancel each other. A robot returns to the origin only if the number of U moves equals the number of D moves and the number of L moves equals the number of R moves. Instead of updating coordinates step by step, iterate through the string and maintain four counters or use built‑in character counts.
After counting, compare the totals: count('U') == count('D') and count('L') == count('R'). If both conditions hold, the robot ends at the origin. This approach focuses on the net displacement rather than the path taken. Since it processes the string once and stores only a few counters, the complexity remains O(n) time and O(1) space.
This counting technique is common in string processing tasks where the relative frequency of characters determines the result. It removes coordinate tracking and makes the logic concise.
Recommended for interviews: Interviewers typically expect the coordinate simulation approach because it clearly models the robot’s movement and demonstrates understanding of grid traversal. The counting approach is equally optimal and slightly shorter, but explaining the cancellation idea shows deeper reasoning about the problem. Both solutions run in O(n) time with constant space, which is optimal for this problem.
Approach 1: Balancing Moves
This approach involves counting the number of moves in each direction and checking if the horizontal movements ('L' and 'R') balance each other and the vertical movements ('U' and 'D') balance each other to return to the origin.
class Solution:
def judgeCircle(self, moves: str) -> bool:
x = y = 0
for move in moves:
if move == 'U': y += 1
elif move == 'D': y -= 1
elif move == 'L': x -= 1
elif move == 'R': x += 1
return x == 0 and y == 0class Solution {
public boolean judgeCircle(String moves) {
int x = 0, y = 0;
for (char move : moves.toCharArray()) {
if (move == 'U') y++;
else if (move == 'D') y--;
else if (move == 'L') x--;
else if (move == 'R') x++;
}
return x == 0 && y == 0;
}
}#include <string>
bool judgeCircle(std::string moves) {
int x = 0, y = 0;
for (char move : moves) {
if (move == 'U') y++;
else if (move == 'D') y--;
else if (move == 'L') x--;
else if (move == 'R') x++;
}
return x == 0 && y == 0;
}var judgeCircle = function(moves) {
let x = 0, y = 0;
for (let move of moves) {
if (move === 'U') y++;
else if (move === 'D') y--;
else if (move === 'L') x--;
else if (move === 'R') x++;
}
return x === 0 && y === 0;
};#include <stdbool.h>
bool judgeCircle(char* moves) {
int x = 0, y = 0;
for (int i = 0; moves[i] != '\0'; i++) {
char move = moves[i];
if (move == 'U') y++;
else if (move == 'D') y--;
else if (move == 'L') x--;
else if (move == 'R') x++;
}
return x == 0 && y == 0;
}public class Solution {
public bool JudgeCircle(string moves) {
int x = 0, y = 0;
foreach (char move in moves) {
switch (move) {
case 'U': y++; break;
case 'D': y--; break;
case 'L': x--; break;
case 'R': x++; break;
}
}
return x == 0 && y == 0;
}
}The Python function uses two variables x and y to keep track of the robot's position. For each character in the input moves, it adjusts the position accordingly. The function returns true if the position is back to the origin after processing all moves.
Time Complexity: O(n), where n is the number of characters in moves.
Space Complexity: O(1), as the space requirement does not increase with input size.
Approach 2: Net Balance Using Counts
Instead of tracking coordinates, this approach counts the occurrences of each move character to determine if the robot returns to the origin. The idea is that the number of 'U' moves should equal 'D' moves and 'L' moves should equal 'R'.
class Solution:
def judgeCircle(self, moves: str) -> bool:
U = moves.count('U')
D = moves.count('D')
L = moves.count('L')
R = moves.count('R')
return U == D and L == Rclass Solution {
public boolean judgeCircle(String moves) {
int U = 0, D = 0, L = 0, R = 0;
for (char move : moves.toCharArray()) {
switch (move) {
case 'U': U++; break;
case 'D': D++; break;
case 'L': L++; break;
case 'R': R++; break;
}
}
return U == D && L == R;
}
}#include <string>
bool judgeCircle(std::string moves) {
int U = 0, D = 0, L = 0, R = 0;
for (char move : moves) {
switch (move) {
case 'U': U++; break;
case 'D': D++; break;
case 'L': L++; break;
case 'R': R++; break;
}
}
return U == D && L == R;
}var judgeCircle = function(moves) {
let U = 0, D = 0, L = 0, R = 0;
for (let move of moves) {
switch (move) {
case 'U': U++; break;
case 'D': D++; break;
case 'L': L++; break;
case 'R': R++; break;
}
}
return U === D && L === R;
};#include <stdbool.h>
#include <string.h>
bool judgeCircle(char* moves) {
int U = 0, D = 0, L = 0, R = 0;
for (int i = 0; moves[i] != '\0'; i++) {
switch (moves[i]) {
case 'U': U++; break;
case 'D': D++; break;
case 'L': L++; break;
case 'R': R++; break;
}
}
return U == D && L == R;
}public class Solution {
public bool JudgeCircle(string moves) {
int U = 0, D = 0, L = 0, R = 0;
foreach (char move in moves) {
switch (move) {
case 'U': U++; break;
case 'D': D++; break;
case 'L': L++; break;
case 'R': R++; break;
}
}
return U == D && L == R;
}
}Using Python string's count method, this solution aggregates move counts directly. The robot is back to the origin if the count of 'U' equals 'D' and the count of 'L' equals 'R'. This method simplifies counting through built-in functions.
Time Complexity: O(n), since count traverses the string each time.
Space Complexity: O(1), accounts for fixed space of integer counters.
Approach 3: Maintain Coordinates
We can maintain a coordinate (x, y) to represent the robot's movement in the horizontal and vertical directions.
Traverse the string moves and update the coordinate (x, y) based on the current character:
- If the current character is
'U', thenyincreases by1; - If the current character is `'D'
, thenydecreases by1; - If the current character is `'L', then
xdecreases by1; - If the current character is `'R'
, thenxincreases by1.
Finally, check if both x and y are 0.
The time complexity is O(n), where n is the length of the string moves. The space complexity is O(1)$.
function judgeCircle(moves: string): boolean {
let [x, y] = [0, 0];
for (const c of moves) {
if (c === 'U') {
y++;
} else if (c === 'D') {
y--;
} else if (c === 'L') {
x--;
} else {
x++;
}
}
return x === 0 && y === 0;
}func judgeCircle(moves string) bool {
x, y := 0, 0
for _, c := range moves {
switch c {
case 'U':
y++
case 'D':
y--
case 'L':
x--
case 'R':
x++
}
}
return x == 0 && y == 0
}Complexity comparison
| Approach | Complexity |
|---|---|
| Balancing Moves | Time Complexity: O(n), where n is the number of characters in |
| Net Balance Using Counts | Time Complexity: O(n), since |
| Maintain Coordinates | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Balancing Moves (Coordinate Simulation) | O(n) | O(1) | Best for interview explanations and grid movement problems where you simulate position changes. |
| Net Balance Using Counts | O(n) | O(1) | Useful when opposite operations cancel out and only final displacement matters. |
Frequently asked questions
Is Robot Return to Origin easy or hard?
Robot Return to Origin is classified as an Easy problem on LeetCode with a high acceptance rate. The challenge mainly tests basic string traversal and simple simulation logic rather than advanced algorithms.
Robot Return to Origin Python/Java solution
In Python or Java, iterate through the string and update coordinates for each move. For example, increment y for 'U', decrement y for 'D', increment x for 'R', and decrement x for 'L'. After the loop, return true if both coordinates equal zero. The implementation runs in O(n) time and O(1) space.
How to solve Robot Return to Origin in O(n)?
Iterate through the move string once and track the robot’s position using two integers for x and y. Increment or decrement the coordinates based on the move character. After processing all moves, return true if x == 0 and y == 0; otherwise return false.
What is the best approach for Robot Return to Origin?
The best approach is simulating the robot's coordinates while iterating through the move string. Update x and y positions for each move (U, D, L, R) and check if both return to zero. This solution runs in O(n) time with O(1) space and clearly models the robot’s movement on a grid.
Is Robot Return to Origin asked at Google/Amazon/Meta?
Robot Return to Origin is a common easy-level interview question used by companies like Amazon and Google to test basic string processing and simulation skills. It checks whether candidates can model movement logic and reason about net displacement efficiently.
What data structure is used in Robot Return to Origin?
The problem typically uses simple variables or counters rather than complex data structures. Most solutions rely on integer variables for coordinates or character frequency counts while iterating through the string.
What is the time complexity of Robot Return to Origin?
The optimal time complexity is O(n), where n is the length of the move string. The algorithm scans the string once and performs constant-time updates for each character. Space complexity is O(1) since only a few counters or coordinate variables are required.
