Robot Return to Origin — LeetCode 657 Python Solution
- Problem
- #657
- Pattern
- Hash Map
- Reading time
- 3 min
- Source
- leetcode.com
The problem
There is a robot starting at the position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.
Example
- Input
- moves = "UD"
- Output
- true
- Explanation
- The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true.
Python solution
class Solution:
def judgeCircle(self, moves: str) -> bool:
x = y = 0
for c in moves:
match c:
case "U":
y += 1
case "D":
y -= 1
case "L":
x -= 1
case "R":
x += 1
return x == 0 and y == 0Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string \textit{moves} |
| Space | O(1) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 657. Robot Return to Origin is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 657. Robot Return to Origin?
- LeetCode 657. Robot Return to Origin is rated Easy on LeetCode.
- What is the time complexity of LeetCode 657. Robot Return to Origin?
- The Python solution on this page runs in O(n), where n is the length of the string \textit{moves}.
- What is the space complexity of LeetCode 657. Robot Return to Origin?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 657. Robot Return to Origin cover?
- LeetCode 657. Robot Return to Origin is tagged String and Simulation on LeetCode.