DDSA Solutions

657. Robot Return to Origin

Time: O(n)
Space: O(1)
Advertisement

Intuition

Track x and y offsets. After all moves, return to origin iff x==0 and y==0.

Algorithm

  1. 1Parse each character: L/R → x--, x++; U/D → y++, y--.
  2. 2Return x==0 && y==0.

Common Pitfalls

  • Simple simulation — no tricks needed.
657.cs
C#
// Approach: Count horizontal (L/R) and vertical (U/D) moves separately;
// return true only if both net displacements are zero.
// Time: O(n) Space: O(1)

public class Solution
{
    public bool JudgeCircle(string moves)
    {
        int right = 0;
        int up = 0;

        foreach (char move in moves)
        {
            switch (move)
            {
                case 'R':
                    right++;
                    break;
                case 'L':
                    right--;
                    break;
                case 'U':
                    up++;
                    break;
                case 'D':
                    up--;
                    break;
            }
        }

        return right == 0 && up == 0;
    }
}
Advertisement
Was this solution helpful?