KatInterview

Bounded Robot Path Under Infinite Command Repeats

Math & Bit ManipulationModel answer
MediumModel answerMath & Bit Manipulationsimulationcycle-detectiongeometry

Last updated

Simulate one pass of a compressed command string, then decide whether infinitely repeating it keeps the robot inside a finite region, even with obstacles.

A robot sits at the origin of an infinite integer grid, facing north. Some cells are permanently blocked by obstacles. The robot is driven by a command string S:

  • G — try to step one cell forward; if that cell is blocked, the robot stays where it is.
  • L / R — rotate 90° left / right.
  • A digit 2–9 placed immediately after a command repeats that command that many times in total (so G3 is three forward steps, R2 is two right turns).

Assume a digit at the very start, two digits in a row, and the digits 0/1 are all invalid input.

Part 1. Execute S once and report the final position (x, y) and the final heading as one of N, E, S, W.

Part 2. Now suppose S is executed over and over forever. Decide whether the set of all cells ever occupied fits inside some fixed finite square — i.e. whether the motion is bounded — and return true/false.

You may not simply simulate until you get bored: your algorithm's running time must not grow with the number of repetitions needed before the answer becomes clear. Give the approach for the obstacle-free case first, then extend it to obstacles, and state time and space complexity in terms of the string length, the obstacle count, and the obstacle bounding box.

Hints

Hint 1

Before thinking about obstacles: turns are unaffected by blocked cells, so the heading after one pass is a fixed rotation. After four passes the heading is guaranteed to be north again — use that as your repeatable unit.

Hint 2

If the robot can't be stopped, one pass is a pure translation. Then boundedness collapses to: did it return to the origin, or is it facing a non-north direction so later passes cancel out?

Hint 3

With obstacles, only the area near them matters. Grow the obstacle bounding box by the maximum possible distance travelled in one super-pass; outside that region blocked cells are irrelevant and motion is exactly a translation, so you can jump ahead analytically instead of stepping.

Hint 4

Inside the safe box there are finitely many positions. If a super-pass ever starts from a position you have already seen, the future is a cycle and the answer is bounded; if the ray from outside never re-enters the box, the answer is unbounded.