LeetCode 657: Robot Return to Origin Solution

Master LeetCode problem 657 (Robot Return to Origin), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

657. Robot Return to Origin

Problem Explanation

Explanation

To solve this problem, we can keep track of the robot's position by incrementing or decrementing its x-coordinate for 'R' and 'L' moves respectively, and its y-coordinate for 'U' and 'D' moves respectively. After processing all the moves, if the robot's final position is back at the origin (0, 0), we return true; otherwise, we return false.

  • Initialize variables for x and y coordinates.
  • Iterate through the moves string, updating the coordinates based on the current move.
  • Check if the final position is at the origin.

Time Complexity: O(n) where n is the length of the moves string. Space Complexity: O(1)

Solution Code

class 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;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 657 (Robot Return to Origin)?

This page provides optimized solutions for LeetCode problem 657 (Robot Return to Origin) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 657 (Robot Return to Origin)?

The time complexity for LeetCode 657 (Robot Return to Origin) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 657 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 657 in Java, C++, or Python.

Back to LeetCode Solutions