09 Sept 2026Go / Python / TypeScriptEasy

Robot Return to Origin

Check whether a sequence of unit moves returns a robot to its starting point.

Track horizontal and vertical displacement while scanning the move string, then test whether both coordinates are zero.

complexity

O(n) time and O(1) extra space.

solution files

  • Go robot-return-to-origin/solution.go
  • Python robot-return-to-origin/solution.py
  • TypeScript robot-return-to-origin/solution.ts

Solution files

Gorobot-return-to-origin/solution.go
package main

func judgeCircle(moves string) bool {
	horizontal, vertical := 0, 0
	for _, move := range moves {
		switch move {
		case 'L':
			horizontal--
		case 'R':
			horizontal++
		case 'U':
			vertical++
		case 'D':
			vertical--
		}
	}
	return horizontal == 0 && vertical == 0
}
Pythonrobot-return-to-origin/solution.py
class Solution:
    def judgeCircle(self, moves: str) -> bool:
        horizontal = vertical = class="syntax-number">0
        for move in moves:
            if move == class="syntax-string">"L": horizontal -= class="syntax-number">1
            elif move == class="syntax-string">"R": horizontal += class="syntax-number">1
            elif move == class="syntax-string">"U": vertical += class="syntax-number">1
            else: vertical -= class="syntax-number">1
        return horizontal == class="syntax-number">0 and vertical == class="syntax-number">0
TypeScriptrobot-return-to-origin/solution.ts
function judgeCircle(moves: string): boolean {
  let horizontal = class="syntax-number">0;
  let vertical = class="syntax-number">0;
  for (const move of moves) {
    if (move === class="syntax-string">"L") horizontal -= class="syntax-number">1;
    else if (move === class="syntax-string">"R") horizontal += class="syntax-number">1;
    else if (move === class="syntax-string">"U") vertical += class="syntax-number">1;
    else vertical -= class="syntax-number">1;
  }
  return horizontal === class="syntax-number">0 && vertical === class="syntax-number">0;
}