#874
Walking Robot Simulation
MediumArrayHash TableSimulationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a set to track obstacles and simulates the robot's movements efficiently. Instead of checking for obstacles at each step, we only check the next position before moving.
⚙️
Algorithm
3 steps- 1Step 1: Initialize the robot's position at (0, 0) and set its initial direction to north.
- 2Step 2: Store obstacles in a set for O(1) lookup time.
- 3Step 3: For each command, adjust the direction for turns and move forward while checking for obstacles only at the next position.
solution.py26 lines
1# Full working Python code
2class Solution:
3 def robotSim(self, commands, obstacles):
4 direction = 0 # 0: North, 1: East, 2: South, 3: West
5 pos = (0, 0)
6 obstacle_set = set(map(tuple, obstacles))
7 max_distance = 0
8 for command in commands:
9 if command == -2: # Turn left
10 direction = (direction + 3) % 4
11 elif command == -1: # Turn right
12 direction = (direction + 1) % 4
13 else: # Move forward
14 for _ in range(command):
15 if direction == 0: # North
16 next_pos = (pos[0], pos[1] + 1)
17 elif direction == 1: # East
18 next_pos = (pos[0] + 1, pos[1])
19 elif direction == 2: # South
20 next_pos = (pos[0], pos[1] - 1)
21 else: # West
22 next_pos = (pos[0] - 1, pos[1])
23 if next_pos not in obstacle_set:
24 pos = next_pos
25 max_distance = max(max_distance, pos[0]**2 + pos[1]**2)
26 return max_distanceℹ
Complexity note: The time complexity is O(n) because we process each command once, and checking for obstacles is O(1) due to the hash set.
- 1Using a set for obstacles allows for O(1) lookups, which is crucial for performance.
- 2Understanding direction changes and how to represent them with simple arrays or vectors can simplify the code.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.