Bounded Robot Path Under Infinite Command Repeats
Math & Bit ManipulationModel answerLast 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–9placed immediately after a command repeats that command that many times in total (soG3is three forward steps,R2is 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
Two ambiguities should be resolved out loud before coding.
Digit meaning. The examples (G3 = three forward steps, R2 = two right turns) show the digit is a total count, not an extra count. Use the examples as the spec.
Validation. Raise an error for a leading digit, two consecutive digits, 0 or 1, and unknown characters. The function returns (x, y, heading, bounded).
Step 1: parse once
Scan S into a list of (command, count) pairs in O(n). This list is reused for every later pass, so parsing cost is paid once.
Step 2: the obstacle-free case (state this first)
Simulate one pass from the origin facing north. Let the heading after the pass be a rotation by r quarter-turns, and let D be the displacement of that pass.
- If
D = (0,0), the robot returns to the origin each pass — bounded. - If
r ≠ 0(the robot is not facing north), the next passes are the same shape rotated; over 2 or 4 passes the displacements cancel and the robot oscillates in a finite region — bounded. - Otherwise (
r = 0,D ≠ 0) every pass adds the same nonzero vector — unbounded.
This is O(n) time, O(1) extra space. Obstacles only complicate it because blocked steps break the pure-translation assumption.
Step 3: handle obstacles with a super-pass
Blocked cells affect only G, so the heading change per pass is still the fixed rotation r. Define a super-pass as S executed 4 times. Every super-pass begins facing north, which means the starting position alone determines the entire future. Let p_{k+1} = f(p_k).
Let M be the number of G commands in one pass (M ≤ 9n). One super-pass travels at most 4M cells.
Key observation. Take the obstacle bounding box, add a margin of 4M on each side, and call the result R. If the robot starts a super-pass outside R, it cannot reach any blocked cell during that super-pass, so the move is a clean translation by a fixed vector D (the obstacle-free super-pass displacement).
Step 4: algorithm
- Simulate one super-pass with obstacles from the origin; record the result and subsequent start positions.
- While the current start position is outside
R:- If
D = (0,0): the robot is at a fixed point — bounded. - Else compute the smallest
k ≥ 1withp + kD ∈ Rin O(1) by intersecting the integerk-intervals for the two axes (lo ≤ p_x + k·D_x ≤ hiand likewise fory). If the intersection is empty, the robot escapes along a ray forever — unbounded. Otherwise jump directly to that entry point.
- If
- Once inside
R, simulate super-passes and record every start position in a set. A repeated start position proves a cycle, hence a finite visited region — bounded. SinceRis finite, this terminates after at most|R|starts.
Axis interval math: for d > 0, k ∈ [ceil((lo−p)/d), floor((hi−p)/d)]; for d < 0, negate and swap bounds; for d = 0, the coordinate is either always in range or never.
Correctness
- Why position is a sufficient state: a super-pass always starts facing north, so
fdepends only on the start position. A repeated position forces the future to repeat, and a cycle lives in a finite set of cells. - Why leaving
Rforever is unbounded: outsideRthe super-pass is exactlyp + kDwithD ≠ 0, which is an unbounded ray. - Why one super-pass bounds the visited cells: every cell visited lies within
4Mof some start position, so bounded starts imply a bounded path. - Termination: each iteration either exhausts a fresh point of the finite region
Ror jumps outside it in O(1), and excursions cannot be infinite without being classified as unbounded.
Complexity
Let n = |S| (so M ≤ 9n), W × H the obstacle bounding box, k the obstacle count.
- Parsing and one pass: O(n) time.
- No obstacles: O(n) time, O(1) space.
- With obstacles: time O(|R| · M) where
|R| = (W + 8M + 1)(H + 8M + 1); space O(|R| + k). - In practice cycles appear after a handful of super-passes. Floyd/Brent cycle detection swaps the visited set for O(1) memory at roughly double the simulation cost.
- Crucially, the number of simulated steps is capped by a function of
nand the obstacle layout — never by how far the robot would wander.
Common mistakes
- Reading a digit as "additional" repeats and producing answers inconsistent with the examples.
- Stepping
Ginto the blocked cell and only then reverting (double-counting) or forgetting that a blocked step costs nothing. - Concluding "bounded" just because the robot comes back near the origin once — with obstacles, only cycle detection inside the finite region is sound.
- Forgetting the possibility that obstacles deflect the robot into a cycle it would otherwise escape, or out of one.
- Missing edge cases: no
Gat all (trivially bounded), a blocked first step (robot stays put), rotation of 180° (returns to north after 2 passes — 4 still works, just uniform), and starting outsideRfrom the very first pass.
Sketch of the core loop (Python):
def bounded(s, obstacles):
ops = parse(s) # list of (cmd, total_count)
blocked = set(map(tuple, obstacles))
x, y, d = run(ops, 0, 0, 0, blocked) # part 1 result
answer1 = (x, y, "NESW"[d])
# part 2: super-pass = 4 passes; margin = 4 * G-count
...