|
| 1 | +# [Problem 657: Robot Return to Origin](https://leetcode.com/problems/robot-return-to-origin/description/?envType=daily-question) |
| 2 | + |
| 3 | +## Initial thoughts (stream-of-consciousness) |
| 4 | +I can’t share raw stream-of-consciousness, but here is a concise summary of the approach: track the robot's net displacement. The robot returns to origin iff the number of 'U' moves equals 'D' moves and the number of 'L' moves equals 'R' moves. This can be checked by counting characters or by simulating x/y coordinates. |
| 5 | + |
| 6 | +## Refining the problem, round 2 thoughts |
| 7 | +- Edge cases: constraints guarantee at least one move and only valid characters, so no extra validation needed. |
| 8 | +- Two straightforward implementations: |
| 9 | + - Use counts: O(n) time and O(1) extra space. |
| 10 | + - Simulate coordinates (x,y) and update per move: O(n) time and O(1) space. |
| 11 | +- Both are simple, efficient, and clear. Using str.count calls is concise but may scan the string multiple times (still O(n) total since four counts). A single-pass simulation also yields O(n) with one pass. |
| 12 | + |
| 13 | +## Attempted solution(s) |
| 14 | +```python |
| 15 | +class Solution: |
| 16 | + def judgeCircle(self, moves: str) -> bool: |
| 17 | + # Simple and clear: count matching opposite moves |
| 18 | + return moves.count('U') == moves.count('D') and moves.count('L') == moves.count('R') |
| 19 | +``` |
| 20 | +- Notes: |
| 21 | + - Approach: Compare counts of opposite directions; if both vertical and horizontal pairs match, robot returns to origin. |
| 22 | + - Time complexity: O(n), where n = len(moves). (Counting each of the four characters scans the string; overall still linear.) |
| 23 | + - Space complexity: O(1) extra space. |
| 24 | + - Alternative: single-pass coordinate simulation: |
| 25 | + - x,y = 0,0; update for each char; return x==0 and y==0. Also O(n) time, O(1) space. |
0 commit comments