JJobsMoi
Jane Street
JA

Walking Robot Simulation

Codingmedium

Problem

A robot starts at the origin (0, 0) on an infinite 2D grid, initially facing north (the positive y direction). You are given an array of commands that the robot executes in order, along with a list obstacles marking grid cells the robot cannot enter.

Each command is one of the following integers:

  • -2: turn the robot 90 degrees to the left (counter-clockwise), without moving.
  • -1: turn the robot 90 degrees to the right (clockwise), without moving.
  • a positive integer k (from 1 to 9): move the robot forward k grid units, one unit at a time, in the direction it is currently facing.

When executing a move command, the robot advances one unit at a time and checks each intermediate cell against the obstacle list. If moving into the next cell would place the robot on an obstacle, the robot must stop before that obstacle (staying at the last valid cell) and skip whatever units remain in that particular move command, then proceed to the next command as normal. Obstacles that never lie on the robot's path have no effect.

Throughout the entire simulation, track the maximum squared Euclidean distance from the origin (0, 0) that the robot ever reaches (that is, x^2 + y^2 for the robot's position after each unit step). Return that maximum value.

Note: the obstacle coordinates are guaranteed not to include the origin, so the robot never starts on an obstacle.

Examples

Example 1:

Input: commands = [4, -1, 3], obstacles = []

Output: 25

Explanation:

  • The robot starts at (0,0) facing north and moves forward 4 units, passing through (0,1), (0,2), (0,3), (0,4).
  • It turns right, now facing east.
  • It moves forward 3 units, reaching (1,4), (2,4), (3,4).
  • The farthest point visited is (3,4), with squared distance 3^2 + 4^2 = 25.

Example 2:

Input: commands = [4, -1, 4, -2, 4], obstacles = [[2,4]]

Output: 65

Explanation:

  • The robot moves north 4 units to (0,4).
  • It turns right (facing east) and tries to move 4 units, but (2,4) is an obstacle, so it can only advance to (1,4) before stopping.
  • It turns left (facing north again) and moves forward 4 units, reaching (1,8).
  • The farthest point is (1,8), giving squared distance 1^2 + 8^2 = 65, which exceeds the squared distance of 17 reached earlier at (1,4).

Constraints

  • 1 <= commands.length <= 10^4
  • commands[i] is -2, -1, or an integer from 1 to 9
  • 0 <= obstacles.length <= 10^4
  • each obstacle is a pair of integers [x, y] with -3 * 10^4 <= x, y <= 3 * 10^4
  • the origin (0, 0) never appears in obstacles
  • no obstacle coordinate pair appears more than once in obstacles

Solution

Loading editor…

Sign in to get AI feedback on your answer. Your work is saved while you do.

Sign in to evaluate