Walking Robot Simulation (LeetCode 874): Solution and Explanation

Medium
Array
Hash Table
Simulation

A robot follows turn and move commands on a grid with obstacles. Return the largest squared distance from the origin it ever reaches.

Intuition

Nothing clever is hiding here: the robot has to be simulated. The only real question is how to check obstacles fast.

Each move command walks at most 9 units, so stepping one square at a time is cheap. Scanning the obstacle list on every step is not, with up to 10^4 obstacles. A hash set of obstacle coordinates answers "is this square blocked?" in O(1).

Directions become an index into a list of four (dx, dy) pairs in clockwise order, so a right turn is +1 and a left turn is +3, both mod 4.

Approach: Step-by-step simulation with a hash set

  1. Put every obstacle in a hash set. Set x = y = 0, d = 0 (north) and best = 0.
  2. For -1, set d = (d + 1) % 4. For -2, set d = (d + 3) % 4.
  3. For a move k, repeat k times: if the next square is in the set, stop this command; otherwise step onto it.
  4. After each move command, set best = max(best, x*x + y*y). Return best.

Step-by-step example

moves = [4,-1,3], obstacles = []
  1. Start at (0, 0) facing north, best = 0.
  2. Move 4: step to (0, 1), (0, 2), (0, 3), (0, 4). best = 16.
  3. -1: turn right, now facing east.
  4. Move 3: step to (1, 4), (2, 4), (3, 4). 9 + 16 = 25, so best = 25.
  5. Return 25.

Code: Python, Java, C++

1class Solution:
2    def robotSim(self, moves: List[int], obstacles: List[List[int]]) -> int:
3        blocked = {(x, y) for x, y in obstacles}
4        dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
5        x = y = d = best = 0
6        for c in moves:
7            if c == -1:
8                d = (d + 1) % 4
9            elif c == -2:
10                d = (d + 3) % 4
11            else:
12                dx, dy = dirs[d]
13                for _ in range(c):
14                    if (x + dx, y + dy) in blocked:
15                        break
16                    x, y = x + dx, y + dy
17                best = max(best, x * x + y * y)
18        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n + m)

n commands, each doing at most 9 constant-time set lookups, plus O(m) to build the set of m obstacles.

Space

O(m)

The obstacle set.

Other approaches

Scan the obstacle list each step (time O(n * m), space O(1))

Check every obstacle before each unit step. Correct but O(9n * m), about 10^9 operations at the limits.

Sorted obstacles per row and column (time O(n log m + m log m), space O(m))

Group obstacles by x and by y and binary search for the nearest one in the walking direction, jumping a whole command at once. Faster for long moves, but moves are at most 9 here, so it is extra code for no gain.

Common mistakes

  • Returning the final distance instead of the maximum over the whole walk.
  • Mixing up the turn codes: -2 is left and -1 is right.
  • Moving the whole k units and then checking for obstacles. The robot must stop in front of the first obstacle on the way.
  • Hashing coordinates badly, for example x * 30000 + y with negative values, which can make two different squares collide.

Frequently asked questions

Why only update best after a move, not after each step?

Along a straight line the squared distance is a convex function, so its maximum on a segment is at one of the two ends. The start was already counted, so checking the end of each move is enough.

What happens with an obstacle at the origin?

The robot starts on it and leaves normally, because only the next square is ever checked. It simply cannot step back onto (0, 0) later.

Why is the parameter called moves here?

LeetCode calls it commands. Our judge reserves that name for design problems, so the parameter is renamed; the order and meaning are the same, so a LeetCode solution works unchanged.