Similar Problems

Similar Problems not available

Robot Return To Origin - Leetcode Solution

Companies:

LeetCode:  Robot Return To Origin Leetcode Solution

Difficulty: Easy

Topics: string simulation  

The Robot Return to Origin problem on LeetCode requires us to determine if a given sequence of instructions will bring a robot back to its starting point (which is at the origin). The robot can move in four directions: North, South, East, and West. The instructions are given as a string where each character represents a movement in one of the four directions.

To solve this problem, we can keep track of the current position of the robot. We can initialize the position of the robot to the origin (0, 0) and then update the position of the robot for each movement in the given instructions.

We can use a pair of variables (x, y) to represent the current position of the robot. We can initialize these variables to zero to represent the origin.

For each movement in the instructions, we can update the position variables according to the movement. For example, if the current movement is 'U' (which represents moving up towards the North direction), we can increment the y-variable by one. Similarly, for a movement 'D' (which represents moving down towards the South direction), we can decrement the y-variable by one. Similarly, for 'L' and 'R' movements (which represent moving towards the West and East directions, respectively), we can update the x-variable accordingly.

After processing all the movements in the given instructions, we can check if the robot has returned to the origin. We can do this by checking if both the x and y variables are zero.

Here's the Python code to implement the above approach:

class Solution:
    def judgeCircle(self, moves: str) -> bool:
        x = 0
        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 == 0

The above code uses the judgeCircle function to take the input moves string. It initializes the position variables x and y to zero. It then loops through each character in the moves string, and updates the position variables based on the current movement. Finally, it returns True if both x and y variables are zero, indicating that the robot has returned to the origin, and False otherwise.

This code has a time complexity of O(N), where N is the length of the input moves string. This is because we process each movement in the string exactly once. The space complexity of the code is O(1), as we only need to store two integers to represent the current position of the robot.

Robot Return To Origin Solution Code

1