Grid Rover Navigation Simulator

Easy · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Implement a 2D fleet navigation simulator with the signature:

def simulate_rover_movement(
    width: int,
    height: int,
    rovers: List[Dict],
    mode: str = "sequential",
) -> List[Dict]:

The arena consists of integer coordinates (x, y) with 0 <= x < width and 0 <= y < height, where (0, 0) represents the south-west corner:

  • "N" points toward +y (step (0, +1))
  • "E" points toward +x (step (+1, 0))
  • "S" points toward -y (step (0, -1))
  • "W" points toward -x (step (-1, 0))

Each entry in rovers is a dictionary {"x": int, "y": int, "heading": str, "commands": str}. Return a list of {"x": int, "y": int, "heading": str} dictionaries reporting the final coordinates and facing direction of every rover in the same order as rovers. Structure your code cleanly with separate abstractions for individual rover kinematics and map-level boundary/occupancy rules (so extending the coordinate system—for instance, to a 3D volume—would require minimal changes).

Validation & Placement Rules

Before executing any command, validate the configuration and place all rovers onto their starting cells:

  • Raise ValueError if width < 0 or height < 0, if mode is neither "sequential" nor "simultaneous", if any rover starts outside the arena bounds, if two rovers share the same starting cell, if any heading is not one of "N", "E", "S", "W" (case-sensitive), or if any character of commands is not one of "L", "R", "M" (case-sensitive).
  • Every rover occupies its current cell at all times—including rovers with empty command strings, rovers waiting for their turn, and rovers that have finished their commands early.

Command & Collision Semantics

Commands in each string run from left to right:

  • "L" rotates the rover 90 degrees counter-clockwise (N -> W -> S -> E -> N) without changing its cell.
  • "R" rotates the rover 90 degrees clockwise (N -> E -> S -> W -> N) without changing its cell.
  • "M" attempts to advance one cell along the rover's current heading. Whenever a forward step is rejected (out of bounds or blocked by occupancy/contention), that "M" becomes a no-op and the rover continues processing any remaining commands.

The mode parameter controls how multiple rovers share time:

  1. "sequential" (default): Rover 0 executes its entire command string from start to finish while rovers 1 .. R - 1 sit on their starting cells; next, rover 1 executes its entire command string while rover 0 sits on its final cell, and so on. An "M" succeeds if and only if the target cell lies inside the arena and is not currently occupied by another rover.
  2. "simultaneous": Execution proceeds in discrete ticks t = 0, 1, 2, .... At tick t, every rover with t < len(commands) executes commands[t]; rovers whose strings have already ended stay parked on their cells. Rotations ("L" and "R") take effect in place without conflict. Forward steps ("M") on tick t are evaluated atomically against the occupancy state at the start of tick t: a rover advances to target if and only if target is inside the arena, was unoccupied when tick t began, and no other rover also attempts to step into target during tick t. Consequently, two rovers targeting the same empty cell, swapping cells head-on, following directly into a cell vacated on the same tick, or rotating around a closed loop all have their "M" steps rejected for that tick, independent of rover list order.

Examples

Example 1

Input:
  width = 4, height = 4
  rovers = [{"x": 2, "y": 2, "heading": "N", "commands": "MMRMMRM"}]
  mode = "sequential"

Output:
  [{"x": 3, "y": 2, "heading": "S"}]

Walk-through: Starting at (2, 2) facing "N" on a 4 x 4 map (x, y in 0..3), the first "M" moves to (2, 3). The second "M" targets (2, 4) (outside the north edge), so it is skipped. "R" faces "E", "M" moves to (3, 3), the next "M" targets (4, 3) (skipped), "R" faces "S", and the final "M" steps to (3, 2).

Example 2

Input:
  width = 4, height = 3
  rovers = [
    {"x": 0, "y": 1, "heading": "E", "commands": "MMRM"},
    {"x": 2, "y": 1, "heading": "N", "commands": "MRM"}
  ]
  mode = "sequential"

Output:
  [{"x": 1, "y": 0, "heading": "S"}, {"x": 3, "y": 2, "heading": "E"}]

Walk-through: Both rovers are placed upfront at (0, 1) and (2, 1). Rover 0 steps east to (1, 1), then tries to enter (2, 1), which is blocked by waiting rover 1 and skipped; rover 0 then turns "S" and moves to (1, 0). Afterward, rover 1 moves north to (2, 2), turns "E", and steps to (3, 2).

Example 3

Input:
  width = 3, height = 3
  rovers = [
    {"x": 0, "y": 1, "heading": "E", "commands": "MRM"},
    {"x": 2, "y": 1, "heading": "W", "commands": "MLM"}
  ]
  mode = "simultaneous"

Output:
  [{"x": 0, "y": 0, "heading": "S"}, {"x": 2, "y": 0, "heading": "S"}]

Walk-through: On tick 0, both rovers execute "M" toward empty cell (1, 1); because two rovers claim the same cell on the same tick, both moves are rejected and they stay at (0, 1) and (2, 1). On tick 1, rover 0 turns "R" to face "S" and rover 1 turns "L" to face "S". On tick 2, they step uncontested into (0, 0) and (2, 0).

Constraints

  • 0 <= width, height <= 10^9 (invalid negative dimensions must raise ValueError)
  • 0 <= len(rovers) <= 10^4
  • Total command characters across all rovers is at most 2 * 10^5.
  • Target complexity: O(R + K) average time and O(R) auxiliary space for R rovers and K total commands (do not allocate a width * height grid array).

Step-by-step walkthrough

  1. Fix the coordinate rules and failure policies

    Before writing code, we lock down every convention the problem asks us to state explicitly. The judge calls simulate_rover_movement(width, height, rovers, mode) where each item in rovers is {"x": int, "y": int, "heading": str, "commands": str}, and expects a list of {"x": int, "y": int, "heading": str} dictionaries in the same rover order.

       +y (N)
        ^
      2 | (0,2) (1,2) (2,2)
      1 | (0,1) (1,1) (2,1)      3 x 3 grid: valid x in 0..2, valid y in 0..2
      0 | (0,0) (1,0) (2,0)
        +------------------> +x (E)
           0     1     2
    
    • Coordinates and compass: (0, 0) is the south-west corner. Valid cells satisfy 0 <= x < width and 0 <= y < height. N increases y (+y), E increases x (+x), S decreases y (-y), and W decreases x (-x).
    • Blocked moves are skipped: if an "M" command would step off the grid or into an occupied cell, that move is ignored and the rover continues with its remaining commands. Example 1 illustrates this: on a 4 x 4 grid (where maximum y is 3), a rover at (2, 3) facing "N" runs "M" and stays at (2, 3) before continuing.
    • Invalid inputs raise ValueError: unknown or lowercase commands, invalid headings, negative grid sizes, out-of-bounds starting cells, overlapping starting cells, or an unknown mode fail immediately before any rover moves.

    Because each command performs only constant-time checks, a clean direct simulation runs in O(K) time for K commands. The real goal is clean separation of responsibilities so multi-rover and 3D extensions plug in naturally.

  2. Model compass turns with a cyclic table

    Instead of writing a four-branch if/elif chain for "N", "E", "S", "W", we list the four compass headings in clockwise order and store the rover's heading as an integer index 0..3:

    index:    0       1       2       3
    heading: "N" <-> "E" <-> "S" <-> "W"   (wraps around at both ends)
    delta:  (0,+1)  (+1,0)  (0,-1)  (-1,0)
    
    Turn right ("R"): (index + 1) % 4
    Turn left  ("L"): (index - 1) % 4   -> from 0 ("N"), (-1) % 4 == 3 ("W") in Python
    

    A Rover only tracks its own (x, y) coordinates and heading_index. It can report where a forward step would land via next_cell(), without knowing anything about grid borders or other rovers.

    # Grid convention: (0, 0) is the south-west corner; N is +y and E is +x.
    # Headings are ordered clockwise so turning right (R) is +1 and left (L) is -1 (mod 4).
    HEADINGS = ["N", "E", "S", "W"]
    # DELTAS[i] is the (dx, dy) step forward when facing HEADINGS[i].
    DELTAS = [(0, 1), (1, 0), (0, -1), (-1, 0)]
    COMMANDS = {"L", "R", "M"}
    MODES = ("sequential", "simultaneous")
    
    
    class Rover:
        """Owns a single rover's position and heading, with no knowledge of the map."""
    
        def __init__(self, x: int, y: int, heading: str):
            self.x = x
            self.y = y
            # Store heading as an integer index 0..3 into HEADINGS for O(1) modular turns.
            self.heading_index = HEADINGS.index(heading)
    
        def turn(self, command: str) -> None:
            # In Python, (-1) % 4 evaluates to 3, wrapping index 0 ("N") cleanly to 3 ("W").
            if command == "L":
                self.heading_index = (self.heading_index - 1) % 4
            else:
                self.heading_index = (self.heading_index + 1) % 4
    
        def cell(self) -> Tuple[int, int]:
            return (self.x, self.y)
    
        def next_cell(self) -> Tuple[int, int]:
            # Compute where "M" would land without mutating the rover yet.
            dx, dy = DELTAS[self.heading_index]
            return (self.x + dx, self.y + dy)
    
        def state(self) -> Dict:
            return {"x": self.x, "y": self.y, "heading": HEADINGS[self.heading_index]}
    
  3. Centralize bounds and collisions in a World class

    To avoid scattering boundary and collision checks across multiple loops, we introduce a World class as the single authority for "can a rover enter this cell?". It stores width, height, and a hash set occupied containing the (x, y) tuple of every rover currently on the map.

    • For a single rover, occupied only holds that rover's own cell, so is_free(target) acts as a pure bounds check.
    • For multiple rovers, occupied holds all rovers' cells, so is_free(target) automatically rejects collisions using the exact same try_move method.
    • _commit removes the old cell, adds the new cell, and updates (rover.x, rover.y) in one place so occupied always matches the fleet's true positions.
    class World:
        """Single authority on map boundaries and cell occupancy."""
    
        def __init__(self, width: int, height: int):
            if width < 0 or height < 0:
                raise ValueError(f"grid dimensions must be non-negative, got {width}x{height}")
            self.width = width
            self.height = height
            # occupied: set of (x, y) tuples for every rover currently on the map (moving or idle).
            self.occupied: Set[Tuple[int, int]] = set()
    
        def in_bounds(self, cell: Tuple[int, int]) -> bool:
            x, y = cell
            # Valid coordinates are 0 .. width - 1 and 0 .. height - 1 (strict < upper bound).
            return 0 <= x < self.width and 0 <= y < self.height
    
        def is_free(self, cell: Tuple[int, int]) -> bool:
            return self.in_bounds(cell) and cell not in self.occupied
    
        def place(self, rover: Rover) -> None:
            cell = rover.cell()
            if not self.in_bounds(cell):
                raise ValueError(f"rover starts outside the map at {cell}")
            if cell in self.occupied:
                raise ValueError(f"two rovers start on {cell}")
            self.occupied.add(cell)
    
        def _commit(self, rover: Rover, target: Tuple[int, int]) -> None:
            # Update the occupancy set and rover coordinates together so they never drift apart.
            self.occupied.remove(rover.cell())
            self.occupied.add(target)
            rover.x, rover.y = target
    
        def try_move(self, rover: Rover) -> bool:
            """Move one rover forward if the target cell is free; return True if it moved."""
            target = rover.next_cell()
            if not self.is_free(target):
                return False
            self._commit(rover, target)
            return True
    
  4. Define sequential vs. simultaneous collision rules

    When several rovers share the map, we must define both when commands execute and how conflicts resolve:

    • Sequential mode: All rovers are placed on the grid before anything moves. Then rover 0 runs its entire command string, followed by rover 1, and so on. Placing everyone upfront matters: a rover waiting for its turn already occupies its starting cell, so an earlier rover cannot drive straight through it.
    • Simultaneous mode: Time advances in discrete ticks t = 0, 1, 2, .... At tick t, every rover that still has a t-th command executes it; rovers with shorter command strings stay parked on their cells. Turning (L/R) happens in place and never conflicts. A forward move (M) succeeds only if its target cell is in bounds, was unoccupied at the start of the tick, and no other rover targets that same cell on this tick.
    Conflict case           Start of tick t         Rule outcome
    ----------------------  ----------------------  ------------------------------------
    Same-tick contention    A -> [empty] <- B       2 claims on target -> BOTH rejected
    Head-on swap            A <---> B               Targets occupied at start -> BOTH rejected
    Following a leader      A -> B -> [empty]       B advances; A's target was occupied -> A waits
    Square 4-cycle          4 rovers chasing tails  All targets occupied at start -> ALL rejected
    

    Checking against the start-of-tick snapshot guarantees that the result never depends on the order in which rovers appear in the input list.

  5. Implement atomic ticks with a two-pass commit

    If we moved rover 0 immediately while deciding tick t, rover 0 would grab contested cells before rover 1 got a look, and rover 0 vacating its cell would let rover 1 follow on the same tick depending on list order. Instead, move_together separates deciding from committing:

    1. Pass 1 (Decide): Without moving any rover, check each mover's next_cell() against self.is_free(target) (the start-of-tick state) and count how many rovers claim each free target cell.
    2. Pass 2 (Commit): Advance only rovers whose target cell has claims[target] == 1.
        def move_together(self, movers: List[Rover]) -> None:
            """Execute one simultaneous tick of 'M' commands independent of rover list order."""
            # Pass 1 (decide): count how many rovers claim each cell that is free at tick start.
            # claims: dict mapping target (x, y) -> number of rovers trying to enter it this tick.
            claims: Dict[Tuple[int, int], int] = {}
            for rover in movers:
                target = rover.next_cell()
                if self.is_free(target):
                    claims[target] = claims.get(target, 0) + 1
    
            # Pass 2 (commit): only a rover that is the sole claimant of its target cell advances.
            # Safe in any order: targets were unoccupied at tick start, and each winner's target is unique.
            for rover in movers:
                target = rover.next_cell()
                if claims.get(target, 0) == 1:
                    self._commit(rover, target)
    
  6. Validate upfront and run either execution mode

    build_world validates every heading, command character, and starting cell before any movement begins, so bad inputs never leave a half-executed state.

    In run_simultaneous, one Rover might have 2 commands while another has 20,000. Instead of looping over every rover on every tick, we maintain active, the list of rover indices that still have commands left. Once a rover's program ends, it drops out of active (while its cell stays in world.occupied), keeping total work proportional to R + total_commands.

    def build_world(width: int, height: int, rovers: List[Dict]) -> Tuple[World, List[Rover], List[str]]:
        """Validate all inputs and place every rover before any command executes."""
        world = World(width, height)
        fleet: List[Rover] = []
        programs: List[str] = []
    
        for spec in rovers:
            heading = spec["heading"]
            if heading not in HEADINGS:
                raise ValueError(f"unknown heading {heading!r}")
            commands = spec["commands"]
            for command in commands:
                if command not in COMMANDS:
                    raise ValueError(f"unknown command {command!r}")
    
            # Placing all rovers upfront ensures waiting rovers block their start cells in sequential mode.
            rover = Rover(spec["x"], spec["y"], heading)
            world.place(rover)
            fleet.append(rover)
            programs.append(commands)
    
        return world, fleet, programs
    
    
    def run_sequential(world: World, fleet: List[Rover], programs: List[str]) -> None:
        """Rover 0 finishes all of its commands, then rover 1, and so on."""
        for rover, commands in zip(fleet, programs):
            for command in commands:
                if command == "M":
                    world.try_move(rover)
                else:
                    rover.turn(command)
    
    
    def run_simultaneous(world: World, fleet: List[Rover], programs: List[str]) -> None:
        """At tick t, every rover that still has a t-th command executes it together."""
        # active: indices of rovers whose command strings have not finished yet.
        active = list(range(len(fleet)))
        tick = 0
    
        while active:
            # Drop rovers whose command strings ended; they stay parked on their current cells.
            # Pruning finished rovers keeps total work O(R + total_commands) instead of O(R * max_len).
            still_active: List[int] = []
            for rover_index in active:
                if tick < len(programs[rover_index]):
                    still_active.append(rover_index)
            active = still_active
            if not active:
                return
    
            # Turns happen in place and never conflict; collect rovers requesting a forward move.
            movers: List[Rover] = []
            for rover_index in active:
                command = programs[rover_index][tick]
                if command == "M":
                    movers.append(fleet[rover_index])
                else:
                    fleet[rover_index].turn(command)
    
            world.move_together(movers)
            tick += 1
    
    
    def simulate_rover_movement(width: int, height: int, rovers: List[Dict], mode: str = "sequential") -> List[Dict]:
        if mode not in MODES:
            raise ValueError(f"unknown mode {mode!r}")
    
        world, fleet, programs = build_world(width, height, rovers)
        if mode == "sequential":
            run_sequential(world, fleet, programs)
        else:
            run_simultaneous(world, fleet, programs)
    
        results: List[Dict] = []
        for rover in fleet:
            results.append(rover.state())
        return results
    
  7. Trace Example 1 and generalize to 3D

    Let's trace Example 1 on a 4 x 4 grid (valid x, y in 0..3) starting at (2, 2) facing "N" with "MMRMMRM":

    Start: (2, 2) N
      M -> (2, 3) N
      M -> target (2, 4) is out of bounds (y = 4 >= 4) -> skipped, stays (2, 3) N
      R -> (2, 3) E
      M -> (3, 3) E
      M -> target (4, 3) is out of bounds (x = 4 >= 4) -> skipped, stays (3, 3) E
      R -> (3, 3) S
      M -> (3, 2) S   --> {"x": 3, "y": 2, "heading": "S"}
    

    When generalizing to a 3D W x H x D volume, our separation of Rover and World pays off because try_move, move_together, run_sequential, and run_simultaneous treat cells as opaque coordinate tuples and need zero algorithmic changes:

    • 3D orientation model: Keep horizontal yaw in the cyclic ["N", "E", "S", "W"] table and add vertical pitch in ["DOWN", "LEVEL", "UP"] (indexed 0, 1, 2). Add commands "U" (pitch up: min(2, pitch + 1)) and "D" (pitch down: max(0, pitch - 1)).
    • 3D step table: When pitch == "LEVEL", next_cell() uses (dx, dy, 0) from yaw; when "UP", (0, 0, +1); when "DOWN", (0, 0, -1). World.in_bounds adds 0 <= z < depth, and _commit updates (rover.x, rover.y, rover.z).
    • Rotational extreme policy: When pointing straight "UP" or "DOWN", horizontal direction cannot be inferred from the movement vector (0, 0, ±1) alone. We clamp "U" at "UP" (and "D" at "DOWN") as a no-op, while keeping yaw stored separately so "L"/"R" still rotate yaw cleanly while vertical.
    3D trace on 3x3x3 from (1,1,0), yaw=N, pitch=LEVEL, commands="UMMULMDM":
      U -> (1,1,0) yaw=N, pitch=UP
      M -> (1,1,1) yaw=N, pitch=UP
      M -> (1,1,2) yaw=N, pitch=UP
      U -> already UP (clamped, ignored)
      L -> (1,1,2) yaw=W, pitch=UP       (yaw still rotates cleanly while vertical)
      M -> target (1,1,3) off map -> skipped
      D -> (1,1,2) yaw=W, pitch=LEVEL    (returns to horizontal with preserved yaw W)
      M -> (0,1,2) yaw=W, pitch=LEVEL
    
  8. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    # Grid convention: (0, 0) is the south-west corner; N is +y and E is +x.
    # Headings are ordered clockwise so turning right (R) is +1 and left (L) is -1 (mod 4).
    HEADINGS = ["N", "E", "S", "W"]
    # DELTAS[i] is the (dx, dy) step forward when facing HEADINGS[i].
    DELTAS = [(0, 1), (1, 0), (0, -1), (-1, 0)]
    COMMANDS = {"L", "R", "M"}
    MODES = ("sequential", "simultaneous")
    
    
    class Rover:
        """Owns a single rover's position and heading, with no knowledge of the map."""
    
        def __init__(self, x: int, y: int, heading: str):
            self.x = x
            self.y = y
            # Store heading as an integer index 0..3 into HEADINGS for O(1) modular turns.
            self.heading_index = HEADINGS.index(heading)
    
        def turn(self, command: str) -> None:
            # In Python, (-1) % 4 evaluates to 3, wrapping index 0 ("N") cleanly to 3 ("W").
            if command == "L":
                self.heading_index = (self.heading_index - 1) % 4
            else:
                self.heading_index = (self.heading_index + 1) % 4
    
        def cell(self) -> Tuple[int, int]:
            return (self.x, self.y)
    
        def next_cell(self) -> Tuple[int, int]:
            # Compute where "M" would land without mutating the rover yet.
            dx, dy = DELTAS[self.heading_index]
            return (self.x + dx, self.y + dy)
    
        def state(self) -> Dict:
            return {"x": self.x, "y": self.y, "heading": HEADINGS[self.heading_index]}
    
    
    class World:
        """Single authority on map boundaries and cell occupancy."""
    
        def __init__(self, width: int, height: int):
            if width < 0 or height < 0:
                raise ValueError(f"grid dimensions must be non-negative, got {width}x{height}")
            self.width = width
            self.height = height
            # occupied: set of (x, y) tuples for every rover currently on the map (moving or idle).
            self.occupied: Set[Tuple[int, int]] = set()
    
        def in_bounds(self, cell: Tuple[int, int]) -> bool:
            x, y = cell
            # Valid coordinates are 0 .. width - 1 and 0 .. height - 1 (strict < upper bound).
            return 0 <= x < self.width and 0 <= y < self.height
    
        def is_free(self, cell: Tuple[int, int]) -> bool:
            return self.in_bounds(cell) and cell not in self.occupied
    
        def place(self, rover: Rover) -> None:
            cell = rover.cell()
            if not self.in_bounds(cell):
                raise ValueError(f"rover starts outside the map at {cell}")
            if cell in self.occupied:
                raise ValueError(f"two rovers start on {cell}")
            self.occupied.add(cell)
    
        def _commit(self, rover: Rover, target: Tuple[int, int]) -> None:
            # Update the occupancy set and rover coordinates together so they never drift apart.
            self.occupied.remove(rover.cell())
            self.occupied.add(target)
            rover.x, rover.y = target
    
        def try_move(self, rover: Rover) -> bool:
            """Move one rover forward if the target cell is free; return True if it moved."""
            target = rover.next_cell()
            if not self.is_free(target):
                return False
            self._commit(rover, target)
            return True
    
        def move_together(self, movers: List[Rover]) -> None:
            """Execute one simultaneous tick of 'M' commands independent of rover list order."""
            # Pass 1 (decide): count how many rovers claim each cell that is free at tick start.
            # claims: dict mapping target (x, y) -> number of rovers trying to enter it this tick.
            claims: Dict[Tuple[int, int], int] = {}
            for rover in movers:
                target = rover.next_cell()
                if self.is_free(target):
                    claims[target] = claims.get(target, 0) + 1
    
            # Pass 2 (commit): only a rover that is the sole claimant of its target cell advances.
            # Safe in any order: targets were unoccupied at tick start, and each winner's target is unique.
            for rover in movers:
                target = rover.next_cell()
                if claims.get(target, 0) == 1:
                    self._commit(rover, target)
    
    
    def build_world(width: int, height: int, rovers: List[Dict]) -> Tuple[World, List[Rover], List[str]]:
        """Validate all inputs and place every rover before any command executes."""
        world = World(width, height)
        fleet: List[Rover] = []
        programs: List[str] = []
    
        for spec in rovers:
            heading = spec["heading"]
            if heading not in HEADINGS:
                raise ValueError(f"unknown heading {heading!r}")
            commands = spec["commands"]
            for command in commands:
                if command not in COMMANDS:
                    raise ValueError(f"unknown command {command!r}")
    
            # Placing all rovers upfront ensures waiting rovers block their start cells in sequential mode.
            rover = Rover(spec["x"], spec["y"], heading)
            world.place(rover)
            fleet.append(rover)
            programs.append(commands)
    
        return world, fleet, programs
    
    
    def run_sequential(world: World, fleet: List[Rover], programs: List[str]) -> None:
        """Rover 0 finishes all of its commands, then rover 1, and so on."""
        for rover, commands in zip(fleet, programs):
            for command in commands:
                if command == "M":
                    world.try_move(rover)
                else:
                    rover.turn(command)
    
    
    def run_simultaneous(world: World, fleet: List[Rover], programs: List[str]) -> None:
        """At tick t, every rover that still has a t-th command executes it together."""
        # active: indices of rovers whose command strings have not finished yet.
        active = list(range(len(fleet)))
        tick = 0
    
        while active:
            # Drop rovers whose command strings ended; they stay parked on their current cells.
            # Pruning finished rovers keeps total work O(R + total_commands) instead of O(R * max_len).
            still_active: List[int] = []
            for rover_index in active:
                if tick < len(programs[rover_index]):
                    still_active.append(rover_index)
            active = still_active
            if not active:
                return
    
            # Turns happen in place and never conflict; collect rovers requesting a forward move.
            movers: List[Rover] = []
            for rover_index in active:
                command = programs[rover_index][tick]
                if command == "M":
                    movers.append(fleet[rover_index])
                else:
                    fleet[rover_index].turn(command)
    
            world.move_together(movers)
            tick += 1
    
    
    def simulate_rover_movement(width: int, height: int, rovers: List[Dict], mode: str = "sequential") -> List[Dict]:
        if mode not in MODES:
            raise ValueError(f"unknown mode {mode!r}")
    
        world, fleet, programs = build_world(width, height, rovers)
        if mode == "sequential":
            run_sequential(world, fleet, programs)
        else:
            run_simultaneous(world, fleet, programs)
    
        results: List[Dict] = []
        for rover in fleet:
            results.append(rover.state())
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of warehouse robots driving across a tiled floor under the supervision of a central floor controller. Each robot (Rover) only remembers its own (x, y) tile and which compass direction it faces, using modular arithmetic (clock-style wraparound math where stepping past the end of a list wraps back to index 0) to turn left or right. Meanwhile, the floor controller (World) owns the room's dimensions and a live checklist of occupied tiles, approving or rejecting every step forward so an invariant (a rule about program state that stays true before and after every step) holds at all times: the occupied set always equals the exact set of rover positions.

Writing a single large loop with nested if heading == "N" branches and inline boundary checks works for one rover, but quickly tangles when adding multiple rovers or a third dimension. Even worse, in simultaneous mode, moving rovers one by one as you scan the list lets earlier rovers grab contested tiles unfairly and lets trailing rovers slip into tiles vacated on the very same tick. Separating Rover from World centralizes collision rules, and using a two-pass atomic commit (applying a group of state updates together only after all checks pass against a shared snapshot) makes simultaneous ticks completely independent of rover order.

Walk through a tiny 3 x 3 example with Rover A at (0, 0) facing "N" (commands = "RM") and Rover B at (1, 1) facing "S" (commands = "M"): - Sequential mode: Both rovers are placed first (occupied = {(0, 0), (1, 1)}). Rover A turns "E" and moves into (1, 0). Then Rover B tries to move south into (1, 0), sees it is occupied, and stays at (1, 1). Final states: A at (1, 0) facing "E", B at (1, 1) facing "S". - Simultaneous mode: At tick 0, Rover A turns "E" at (0, 0) while Rover B is the sole claimant for free cell (1, 0) and moves there. At tick 1, Rover A tries to move east into (1, 0), sees it was occupied at the start of tick 1, and stays at (0, 0). Final states: A at (0, 0) facing "E", B at (1, 0) facing "S".

Complexity

Let R be the number of rovers and K be the total number of command characters across all rovers.

  • Time: O(R + K) on average in both modes. Validating and placing all rovers scans the R rovers and K command characters once. During execution, each turn does constant-time index math, and each forward move does constant-time boundary math plus one or two average O(1) hash-set/dictionary lookups. In simultaneous mode, finished rovers are pruned from the active list as soon as their command strings end, so each tick only touches rovers that still have commands to run rather than scanning all R rovers every tick.
  • Space: O(R) auxiliary memory beyond the input. We store R Rover objects, at most R coordinates in world.occupied, and at most R entries in a single tick's claims dictionary; the width x height grid itself is never allocated as a 2D array.

Edge cases

  • Empty fleet or empty command string: rovers = [] returns []; a rover with commands = "" stays on its starting cell with its initial heading and still blocks other rovers from entering that cell.
  • Boundary-hugging moves: A rover on the edge facing outward skips "M" and still executes subsequent turns and inward moves (as in Example 1).
  • 1 x 1 grid: Every "M" command is out of bounds and skipped, while "L" and "R" still update the heading.
  • Unequal command lengths in simultaneous mode: A rover whose commands finish early stops participating in future ticks while continuing to occupy its final cell.
  • Simultaneous contention, head-on swaps, and cycles: Two rovers claiming the same free cell (Example 3), two rovers trying to swap cells, and four rovers rotating around a 2 x 2 square are all rejected cleanly without moving any of them.
  • Malformed inputs: Unknown or lowercase commands, bad headings, negative grid dimensions, out-of-bounds starts, duplicate starting cells, or an unknown mode raise ValueError before any rover moves.

Common mistakes

  • Swapping left and right turns: In clockwise order ["N", "E", "S", "W"], "R" is +1 and "L" is -1. Reversing them still passes symmetric square loops, which hides the bug until an asymmetric path like Example 1.
  • Off-by-one upper bounds: Valid coordinates on a grid of width W are 0 <= x < W, not 0 <= x <= W. Allowing x == W gives the map W + 1 columns.
  • Placing sequential rovers lazily: If you only add a rover to occupied when its turn starts, Rover 0 can drive right through Rover 1's starting cell before Rover 1 exists on the map.
  • Mutating occupied mid-tick in simultaneous mode: Updating positions inside a single loop makes input order decide who wins a contested cell and whether a follower can step into a cell vacated on the same tick.
  • Losing horizontal yaw at vertical pitch in 3D: If you store 3D orientation only as a unit direction vector (dx, dy, dz), pointing straight up (0, 0, 1) erases which horizontal way the rover was facing. Storing yaw separately avoids this ambiguity.

Alternative approaches

  • Allow same-tick convoy following: You can permit Rover A to enter Rover B's cell on the same tick if Rover B also successfully moves out of that cell. To implement this, resolve chains of moves iteratively (rejecting any mover aimed at a stationary or blocked rover until no more rejections occur) and decide explicitly whether closed cycles like 2-rover swaps or 4-rover loops are allowed.
  • Priority tie-breaking on contested cells: Instead of rejecting all claimants when two rovers target the same empty cell on the same tick, a warehouse scheduler might grant the cell to the lowest-indexed or highest-priority rover. That increases throughput, at the cost of making list/priority order part of the specification.
  • Full 3D orientation with 24 axis-aligned states: Instead of yaw + pitch with clamping, you can track two perpendicular 3D unit vectors (forward and up) and support yaw (L/R), pitch (U/D), and roll (CW/CCW) via 3D vector cross products, avoiding gimbal clamping altogether at the cost of more complex mental tracing.

Follow-up questions

  • If static blocked tiles are introduced on the grid, which classes change and how is the boundary between Rover and World preserved? Only World (and build_world to load the obstacle coordinates) needs to change; Rover, try_move, move_together, and both runners stay completely untouched. Add self.obstacles: Set[Tuple[int, int]] to World, check cell not in self.obstacles inside is_free and place, and keep obstacles in their own set separate from self.occupied so the invariant "occupied equals the set of rover positions" stays clean.
  • When simultaneous rovers obstruct one another's forward steps, how would you handle or detect a mutual standstill under skip, retry, or fail-fast policies? Under our "skip blocked moves" policy, a deadlock (a standstill where two or more agents wait forever because each blocks what the other needs) cannot happen because every tick consumes one command per active rover regardless of whether the move succeeded. Deadlock arises if you switch to a "retry the blocked command on the next tick" policy: detect it whenever a full tick finishes with zero turns and zero successful moves (caused by a cycle in the wait-for graph, a directed diagram where an arrow from A to B means A cannot advance until B vacates its cell, or by waiting behind a finished rover). Once detected, you can either skip one blocked command by priority, route around the blocker, or raise a deadlock error depending on product requirements.
  • How would you adapt the simulator to a vast, mostly empty 3D coordinate space (such as 10^9 units per axis) where allocating a grid array is impossible? Our World already avoids allocating a dense grid: bounds checks are simple integer comparisons (0 <= x < width) and occupied is a hash set of (x, y, z) tuples, so memory stays O(R) even on a 10^9 x 10^9 x 10^9 map. Point obstacles also fit in a hash set, while large box-shaped obstacles can be stored in a spatial index (a data structure, such as an octree or per-axis sorted intervals, that groups coordinates so empty space can be skipped quickly). If command strings compress long straight runs like "M1000000", binary-searching sorted blockers along that axis line lets a rover jump directly to the cell before the first obstacle or border in O(log(R + obstacles)) time.
  • If you were handed an unverified auto-generated implementation of this simulator, what invariants and targeted test cases would you check before shipping it? First, verify every stated contract line by line: coordinate axes, clockwise vs. counter-clockwise turn direction, exclusive upper bounds (< width vs. <= width), negative modulo behavior, and whether invalid inputs mutate state before raising. Next, add targeted unit tests for four-turn wraparounds ("LLLL" and "RRRR"), all four map borders, stationary rovers blocking moving ones, head-on swaps, and contested cells. Finally, assert state invariants after every step in debug mode (len(world.occupied) == len(fleet) and every rover is in bounds and in occupied), check that shuffling input rovers in simultaneous mode permutes outputs identically, and run randomized fuzz tests against a tiny list-based reference simulator.

Follow-up questions

Similar questions

More Shopify interview questions

All 63 Shopify questions →