Skip to main content
impol.dev

Editorial

Solution walkthrough

Review the explanation, then compare the reference implementation.

Video explanation

Solution

Intuition

Each movement command is short, so simulate it one unit at a time. A hash set makes obstacle checks direct, while cycling through north, east, south, and west turns orientation changes into simple index updates. We need the greatest distance visited, not just the final distance.

Approach

  1. Store obstacle coordinates in a set. Begin at the origin facing north.
  2. Turn left or right by changing the direction index modulo four.
  3. For a forward command, inspect each next cell before moving. Stop that command at the first obstacle; otherwise move and update the maximum x*x + y*y.
  4. Return the maximum. An obstacle at the origin does not prevent starting there, because only destination cells are checked, but it prevents returning after departure.
class Solution: def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int: dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)] # NESW d = 0 x, y = 0, 0 res = 0 obs = set() for a, b in obstacles: obs.add((a, b)) for c in commands: if c == -2: d = (d - 1) % 4 elif c == -1: d = (d + 1) % 4 else: for _ in range(c): nx, ny = x + dirs[d][0], y + dirs[d][1] if (nx, ny) in obs: break res = max(res, nx**2 + ny**2) x, y = nx, ny return res

Complexity analysis

Let C be the number of commands, S the sum of positive movement distances, and O the number of obstacles. Building the obstacle set and simulating steps takes O(C + S + O) time and O(O) auxiliary space.