algoadvance

You are given a string moves that represents the movements of a robot on a 2D plane. The robot starts at the origin point (0, 0), and each character in the string moves it as follows:

Return True if the robot returns to the origin after completing all of its moves, or False otherwise.

Clarifying Questions

  1. What are the constraints on the string length?
    • The length of moves will be between 1 and 10^4.
  2. Will the string only contain the characters ‘U’, ‘D’, ‘L’, and ‘R’?
    • Yes, the string will only consist of the characters ‘U’, ‘D’, ‘L’, and ‘R’.

Strategy

  1. Initialize a starting position: Use variables x and y to track the robot’s position, starting both at 0.
  2. Iterate through the string: For each move in the string, update the x and y coordinates according to the move.
  3. Check the final position: After processing all moves, check if the robot’s position is back at the origin (0, 0).
  4. Return the result: If the position is (0, 0), return True; otherwise, return False.

Code

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

Time Complexity

Try our interview co-pilot at AlgoAdvance.com