File: robot-return-to-origin/solution.py

Date: 2026-06-06

Time: 18:56

robot-return-to-origin/solution.py

Purpose

This file solves LeetCode #657 — Robot Return to Origin. It determines whether a sequence of moves (U/D/L/R) on a 2D grid returns a robot to its starting position (0, 0). It's a standalone solution module following the repo's convention of one problem per directory.

Key Components

judgeCircle(moves: str) -> bool — The sole function. It checks whether the robot ends at the origin by verifying two independent conditions:

1. Horizontal balance: count('L') == count('R')

2. Vertical balance: count('U') == count('D')

Both must hold for the robot to return. The function is a pure expression with no mutation or side effects.

Patterns

Dependencies

Imports: None — pure stdlib, no external dependencies.

Imported by: robot-return-to-origin/test_solution.py directly. The massive "Imported By" list in the prompt is misleading — those are unrelated test files that share the same test harness infrastructure, not actual consumers of judgeCircle.

Flow

1. str.count('L') scans the full string — O(n).

2. str.count('R') scans again — O(n).

3. If counts differ, short-circuit returns False (Python and).

4. Otherwise, str.count('U') and str.count('D') are compared — two more O(n) scans.

Total: 2–4 linear passes over moves. Worst case is 4n character comparisons. No allocations beyond the integer counts.

Invariants

Error Handling

None. Invalid characters (e.g., 'X') are silently ignored by str.count — they simply don't match any of the four counted characters. An empty string returns True (0 == 0 for all pairs), which is correct: no moves means the robot stays at the origin.

Topics to Explore

Beliefs