Ctrl K

How Far the Rover Got

Medium
A rover stands at (0, 0) on an infinite grid plain, facing north (the +Y direction; east is +X). It runs the commands in commands one by one: - -2: turn left by 90°; - -1: turn right by 90°; - an integer k from 1 to 9: drive forward k cells, one cell at a time. Some cells hold rocks; their coordinates are listed in rocks. If the next cell holds a rock, the rover stays where it is and moves on to the next command. A rock may even sit at (0, 0): it does not prevent the start, but the rover can never return there. Return the largest squared distance from the origin (x² + y²) the rover ever reaches.
Example 1
commands=[3, -2, 2, -2, 5], rocks=[[-2, 0]] → 13

The rover drives north to (0, 3), turns left and goes west to (-2, 3), then turns left again heading south: (-2, 2), (-2, 1); the next cell (-2, 0) holds a rock, so it stops. Its farthest point was (-2, 3): 4 + 9 = 13.

Example 2
commands=[2, -1, -1, 4], rocks=[[0, 0]] → 4

A rock at the origin does not stop the start. The rover climbs to (0, 2), turns around and heads south, but halts at (0, 1) in front of the rock. The answer is 4.

Example 3
commands=[-1, 1, -1, 1], rocks=[] → 2
Constraints
  • 1 ≤ len(commands) ≤ 10⁴
  • commands[i] is -2, -1 or an integer from 1 to 9
  • 0 ≤ len(rocks) ≤ 10⁴
  • -3·10⁴ ≤ rock coordinates ≤ 3·10⁴
  • The answer is less than 2³¹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLast Step With a Lit Run MediumFully Dug Relics MediumA Chain of Replacements MediumRows That Match Columns MediumJobs in Order With Rest Days Medium
loading Python…
Input
commands=[3, -2, 2, -2, 5], rocks=[[-2, 0]]
Expected
13

Run checks the first 3 tests in your browser. Submit checks all 98 tests on the server, hidden ones included.