#1041
Robot Bounded In Circle
MediumMathStringSimulationSimulationCoordinate Geometry
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages the observation that if the robot returns to the origin or changes its direction after one complete set of instructions, it will remain bounded in a circle. This avoids unnecessary iterations.
⚙️
Algorithm
3 steps- 1Step 1: Initialize the robot's position at (0, 0) and direction facing north.
- 2Step 2: Execute the instructions once to find the final position and direction.
- 3Step 3: If the robot is back at the origin or not facing north, return true; otherwise, return false.
solution.py14 lines
1def isRobotBounded(instructions):
2 x, y = 0, 0
3 direction = 0 # 0: North, 1: East, 2: South, 3: West
4 for instruction in instructions:
5 if instruction == 'G':
6 if direction == 0: y += 1
7 elif direction == 1: x += 1
8 elif direction == 2: y -= 1
9 else: x -= 1
10 elif instruction == 'L':
11 direction = (direction + 3) % 4
12 elif instruction == 'R':
13 direction = (direction + 1) % 4
14 return (x == 0 and y == 0) or direction != 0ℹ
Complexity note: The time complexity is O(n) because we process each instruction exactly once, and the space complexity is O(1) since we only use a fixed amount of space for variables.
- 1The robot stays bounded if it returns to the origin or changes direction after one complete set of instructions.
- 2The movement and turning can be effectively modeled using simple coordinate changes.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.