Multi-Rover Grid Command Controller

Easy · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Implement an in-memory command processor that manages a fleet of surface rovers operating on an unbounded 2D integer grid (+y points North "N", +x points East "E", -y points South "S", and -x points West "W").

Complete Rover, RoverController, and split_command in starter.py:

  1. Single-rover state (Rover)

    • Every rover spawns at (x=0, y=0) with facing="N".
    • turn_left() rotates the heading 90 degrees counter-clockwise (N -> W -> S -> E -> N).
    • turn_right() rotates the heading 90 degrees clockwise (N -> E -> S -> W -> N).
    • cell_ahead() returns the (x, y) coordinates one step forward in self.facing without mutating the rover.
    • move_to(cell) updates (self.x, self.y) to cell, and state() returns (self.x, self.y, self.facing).
  2. Comment stripping (split_command(line) -> List[str])

    • Strips everything from the first # character to the end of line and returns the whitespace-separated tokens that remain.
  3. Fleet management, collision blocking, and reporting (RoverController)

    • Command keywords are case-insensitive (select and SELECT are equivalent), while rover <id> tokens are case-sensitive (r1 and R1 are distinct):
      • CREATE <id>: adds a new rover <id> at (0, 0) facing "N" without changing self.selected. Fails with duplicate_id if <id> already exists. Newly created rovers may coexist at (0, 0).
      • DELETE <id>: removes <id> from self.rovers; if self.selected == <id>, resets self.selected to None. Fails with no_such_rover if <id> is absent.
      • SELECT <id>: sets self.selected = <id>. Fails with no_such_rover if <id> is absent.
      • L, R, M: turns left, turns right, or advances the selected rover one step forward. Fails with no_selection when self.selected is None. Executing M fails with blocked whenever another existing rover occupies cell_ahead(), leaving the active rover's coordinates and heading unchanged.
    • Argument & command checks: CREATE, DELETE, and SELECT require exactly 1 argument (bad_arguments otherwise); L, R, and M take 0 arguments (bad_arguments otherwise). Any other command name — or an empty/comment-only string passed directly to execute(line) — fails with unknown_command. Failed commands never modify state.
    • Report format: execute(line) returns "OK <state>" on success or "ERROR <code> <state>" on failure, where <state> is "<id> <x> <y> <dir>" for self.selected, or "-" when self.selected is None.
    • Batch execution: run(lines) skips blank and comment-only lines, calls execute on each remaining line in order, and returns the list of report strings.

Examples

Example 1

Input:

CREATE r1
SELECT r1
R
M
CREATE r2
SELECT r2
R
M # blocked by r1 at (1, 0)
L
M

Output:

[
    "OK -",
    "OK r1 0 0 N",
    "OK r1 0 0 E",
    "OK r1 1 0 E",
    "OK r1 1 0 E",
    "OK r2 0 0 N",
    "OK r2 0 0 E",
    "ERROR blocked r2 0 0 E",
    "OK r2 0 0 N",
    "OK r2 0 1 N",
]

Explanation: r1 spawns at (0, 0, N), turns East, and advances to (1, 0, E). Creating r2 places it at (0, 0, N) while r1 stays selected (OK r1 1 0 E). After selecting r2 and turning East, M targets (1, 0) where r1 is parked, returning ERROR blocked r2 0 0 E without moving r2. Turning left to North and stepping forward moves r2 into the unoccupied cell (0, 1).

Example 2

Input:

M
CREATE scout
SELECT scout
L
M
SELECT unknown
DELETE scout
R

Output:

[
    "ERROR no_selection -",
    "OK -",
    "OK scout 0 0 N",
    "OK scout 0 0 W",
    "OK scout -1 0 W",
    "ERROR no_such_rover scout -1 0 W",
    "OK -",
    "ERROR no_selection -",
]

Explanation: Driving before any selection returns ERROR no_selection -. After scout turns West and moves to (-1, 0), SELECT unknown fails without changing the active selection (scout -1 0 W). Deleting scout clears self.selected back to None (OK -), so the final R reports ERROR no_selection -.

Constraints

  • Grid coordinates (x, y) are unbounded signed integers and may be negative, zero, or arbitrarily large.
  • Rover IDs are non-empty, whitespace-free, case-sensitive strings; command keywords are case-insensitive.
  • Error codes must be exact: unknown_command, bad_arguments, duplicate_id, no_such_rover, no_selection, blocked.
  • Collision checks apply only to forward moves (M), not to CREATE, L, or R.

Step-by-step walkthrough

  1. Pin down an unambiguous command and output contract

    Before writing simulation logic, make every parsing and reporting detail explicit so there are zero edge-case ambiguities:

    • Input syntax: one command per line. Command keywords (CREATE, DELETE, SELECT, L, R, M) are case-insensitive (select r1 and SELECT r1 both work), while rover IDs are case-sensitive tokens without whitespace (r1 and R1 are distinct rovers). Everything from # through the end of a line is stripped as an inline comment, allowing annotated lines like M # blocked by r1 at (1, 0) to execute cleanly.
    • Output format: every executed command produces one space-delimited report string:
      • OK <state> on success, or
      • ERROR <code> <state> on failure, where <state> is <id> <x> <y> <dir> for the active rover, or - when no rover is selected.
    • Error codes: unknown_command, bad_arguments, duplicate_id, no_such_rover, no_selection, and blocked.
    • State invariants (rules that always hold):
      1. A failed command never modifies any rover or self.selected.
      2. CREATE <id> spawns a rover at (0, 0) facing N without changing self.selected.
      3. Deleting the currently selected rover resets self.selected back to None.
      4. Multiple newly created rovers may coexist at (0, 0); collision blocking applies specifically when executing M.
    Input command   ->  Returned report line
    ---------------------------------------------------
    CREATE r1       ->  OK -
    SELECT r1       ->  OK r1 0 0 N
    M               ->  OK r1 0 1 N
    SELECT unknown  ->  ERROR no_such_rover r1 0 1 N
    
  2. Model a single rover on the 2D grid

    Keep the Rover class focused exclusively on one rover's coordinates and compass heading, completely decoupled from text parsing or I/O.

    Instead of maintaining two separate 4-branch if/elif chains for left and right rotations, store the four compass headings clockwise in DIRECTIONS = ["N", "E", "S", "W"]. Turning right steps +1 around this list, turning left steps -1, and % 4 (modulo 4) wraps around both ends automatically. Because (-1) % 4 == 3 in Python, turning left from "N" (index 0) lands directly on "W" (index 3).

    Splitting movement into cell_ahead() (computing the next square without mutating self.x or self.y) and move_to(cell) makes look-ahead collision checking effortless.

              N (0, +1)
                ^
                |
    W (-1, 0) <-+-> E (+1, 0)     DIRECTIONS = ["N", "E", "S", "W"]
                |                 turn_right: (index + 1) % 4
                v                 turn_left:  (index - 1) % 4
              S (0, -1)
    
    from typing import Tuple
    
    # Headings stored in clockwise order around the compass: North -> East -> South -> West.
    # Turning right steps +1 around this list; turning left steps -1.
    DIRECTIONS = ["N", "E", "S", "W"]
    
    # STEPS maps each compass heading to its (dx, dy) grid offset for one forward step.
    # North increases y, East increases x, South decreases y, and West decreases x.
    STEPS = {"N": (0, 1), "E": (1, 0), "S": (0, -1), "W": (-1, 0)}
    
    
    class Rover:
        """One rover on an unbounded 2D grid. Starts at (0, 0) facing North."""
    
        def __init__(self) -> None:
            # Unbounded integer coordinates and a single-letter heading from DIRECTIONS.
            self.x = 0
            self.y = 0
            self.facing = "N"
    
        def turn_left(self) -> None:
            # In Python, (-1) % 4 evaluates to 3, so stepping back from index 0 ("N")
            # wraps cleanly to index 3 ("W") without needing a special-case branch.
            current_index = DIRECTIONS.index(self.facing)
            next_index = (current_index - 1) % 4
            self.facing = DIRECTIONS[next_index]
    
        def turn_right(self) -> None:
            # Stepping forward from index 3 ("W") wraps via 4 % 4 == 0 back to "N".
            current_index = DIRECTIONS.index(self.facing)
            next_index = (current_index + 1) % 4
            self.facing = DIRECTIONS[next_index]
    
        def cell_ahead(self) -> Tuple[int, int]:
            # Compute the destination cell WITHOUT mutating self.x or self.y,
            # so the controller can check for collisions before moving the rover.
            dx, dy = STEPS[self.facing]
            return (self.x + dx, self.y + dy)
    
        def move_to(self, cell: Tuple[int, int]) -> None:
            self.x, self.y = cell
    
        def state(self) -> Tuple[int, int, str]:
            return (self.x, self.y, self.facing)
    
  3. Manage multiple rovers and active selection

    RoverController tracks the fleet with two fields: 1. self.rovers: dictionary mapping each rover_id string to its Rover object. 2. self.selected: ID string of the active rover, or None when none is selected.

    Each lifecycle helper (_create, _delete, _select) checks preconditions before mutating state, returning None on success or an error code string on failure. In _delete, remember to clear self.selected = None whenever the deleted rover was the active one — otherwise the next command or status report would crash with KeyError.

    from typing import Optional
    
    
    def _create(self, rover_id: str) -> Optional[str]:
        if rover_id in self.rovers:
            return "duplicate_id"
        # Multiple newly created rovers may share (0, 0); collisions apply only to 'M' moves.
        self.rovers[rover_id] = Rover()
        return None
    
    
    def _delete(self, rover_id: str) -> Optional[str]:
        if rover_id not in self.rovers:
            return "no_such_rover"
        del self.rovers[rover_id]
        # Clear selection if we just deleted the active rover, preventing a dangling ID.
        if self.selected == rover_id:
            self.selected = None
        return None
    
    
    def _select(self, rover_id: str) -> Optional[str]:
        if rover_id not in self.rovers:
            return "no_such_rover"
        self.selected = rover_id
        return None
    
  4. Add look-ahead collision avoidance

    When L, R, or M runs, _drive first checks self.selected is not None. Rotations (L and R) spin in place and never collide.

    For M, we query target_cell = rover.cell_ahead() and scan self.rovers to check whether any other rover already occupies target_cell. Why scan self.rovers instead of keeping a plain Python set of occupied coordinates? Because two newly created rovers r1 and r2 both start at (0, 0). If r1 drove away and deleted (0, 0) from a plain set, the controller would forget that r2 is still parked at (0, 0)! Reading self.rovers directly keeps a single source of truth.

    Before 'M' on rover r2:           Target check:
      y=0 | [r2 facing E] [r1]         r2.cell_ahead() -> (1, 0)
          +--------------------        rover 'r1' already occupies (1, 0) -> return "blocked"
             x=0           x=1         'r2' stays at (0, 0) facing E
    
    from typing import Optional, Tuple
    
    
    def _drive(self, command_name: str) -> Optional[str]:
        if self.selected is None:
            return "no_selection"
        rover = self.rovers[self.selected]
        if command_name == "L":
            rover.turn_left()
        elif command_name == "R":
            rover.turn_right()
        else:
            # Look ahead before moving so a blocked move leaves the rover completely untouched.
            target_cell = rover.cell_ahead()
            if self._occupied_by_other(target_cell, self.selected):
                return "blocked"
            rover.move_to(target_cell)
        return None
    
    
    def _occupied_by_other(self, cell: Tuple[int, int], moving_rover_id: str) -> bool:
        # Check every other existing rover's coordinates; scanning self.rovers handles
        # multiple rovers stacked at (0, 0) without needing a separate cell-count map.
        for other_id, other_rover in self.rovers.items():
            if other_id != moving_rover_id and (other_rover.x, other_rover.y) == cell:
                return True
        return False
    
  5. Parse lines, dispatch commands, and format reports

    Now connect raw input lines to the controller methods:

    • split_command(line) removes any # comment via line.split("#", 1)[0] and splits remaining whitespace-delimited words.
    • execute(line) validates argument counts (1 argument for CREATE/DELETE/SELECT, 0 arguments for L/R/M) so malformed lines like CREATE a b, M 3, or LL return clean error reports.
    • _report(error_code) formats <id> <x> <y> <dir> for self.selected (or - when None) and prepends OK or ERROR <code>.
    • run(lines) skips blank or comment-only lines and collects one report string per executed command.
    from typing import Iterable, List, Optional
    
    
    def split_command(line: str) -> List[str]:
        """Words of a command line, with any '#' comment removed."""
        # Split at the first '#' only (maxsplit=1) so everything after '#' is ignored as a comment.
        without_comment = line.split("#", 1)[0]
        return without_comment.split()
    
    
    def execute(self, line: str) -> str:
        # Phase 1: tokenize the command line after stripping any '#' comment.
        words = split_command(line)
        if not words:
            return self._report("unknown_command")
    
        # Normalize the command keyword to uppercase while keeping rover IDs case-sensitive.
        command_name = words[0].upper()
        args = words[1:]
    
        # Phase 2: validate argument counts and dispatch management commands.
        if command_name in ("CREATE", "DELETE", "SELECT"):
            if len(args) != 1:
                return self._report("bad_arguments")
            rover_id = args[0]
            if command_name == "CREATE":
                error_code = self._create(rover_id)
            elif command_name == "DELETE":
                error_code = self._delete(rover_id)
            else:
                error_code = self._select(rover_id)
            return self._report(error_code)
    
        # Phase 3: validate argument counts and dispatch movement/turn commands.
        if command_name in ("L", "R", "M"):
            if len(args) != 0:
                return self._report("bad_arguments")
            error_code = self._drive(command_name)
            return self._report(error_code)
    
        return self._report("unknown_command")
    
    
    def run(self, lines: Iterable[str]) -> List[str]:
        """Execute every non-blank line; blank and comment-only lines produce no report."""
        reports: List[str] = []
        for line in lines:
            # Skip blank lines and comment-only lines when running a multi-line script.
            if split_command(line):
                reports.append(self.execute(line))
        return reports
    
    
    def _report(self, error_code: Optional[str]) -> str:
        # Every command reports the currently selected rover's state, or "-" if none is selected.
        if self.selected is None:
            state_text = "-"
        else:
            x, y, facing = self.rovers[self.selected].state()
            state_text = f"{self.selected} {x} {y} {facing}"
    
        if error_code is None:
            return f"OK {state_text}"
        return f"ERROR {error_code} {state_text}"
    
  6. Trace Example 1 step by step

    Let's walk through all 10 commands of Example 1 to verify positions, headings, and collision handling:

    Command                         Rover r1    Rover r2    Selected   Returned report
    ----------------------------------------------------------------------------------------------
    CREATE r1                       (0, 0) N    -           None       OK -
    SELECT r1                       (0, 0) N    -           r1         OK r1 0 0 N
    R                               (0, 0) E    -           r1         OK r1 0 0 E
    M                               (1, 0) E    -           r1         OK r1 1 0 E
    CREATE r2                       (1, 0) E    (0, 0) N    r1         OK r1 1 0 E
    SELECT r2                       (1, 0) E    (0, 0) N    r2         OK r2 0 0 N
    R                               (1, 0) E    (0, 0) E    r2         OK r2 0 0 E
    M # blocked by r1 at (1, 0)     (1, 0) E    (0, 0) E    r2         ERROR blocked r2 0 0 E
    L                               (1, 0) E    (0, 0) N    r2         OK r2 0 0 N
    M                               (1, 0) E    (0, 1) N    r2         OK r2 0 1 N
    

    When r2 faces East at (0, 0), r2.cell_ahead() is (1, 0), which r1 already occupies — so execute returns ERROR blocked r2 0 0 E without changing r2's state. Turning left to "N" aims r2 at the empty cell (0, 1), so the final M succeeds.

  7. Assemble the complete solution

    Combining Rover, RoverController, split_command, and the sys.stdin runner gives the complete implementation:

    from typing import Dict, Iterable, List, Optional, Tuple
    import sys
    
    # Headings stored in clockwise order around the compass: North -> East -> South -> West.
    # Turning right steps +1 around this list; turning left steps -1.
    DIRECTIONS = ["N", "E", "S", "W"]
    
    # STEPS maps each compass heading to its (dx, dy) grid offset for one forward step.
    # North increases y, East increases x, South decreases y, and West decreases x.
    STEPS = {"N": (0, 1), "E": (1, 0), "S": (0, -1), "W": (-1, 0)}
    
    
    class Rover:
        """One rover on an unbounded 2D grid. Starts at (0, 0) facing North."""
    
        def __init__(self) -> None:
            # Unbounded integer coordinates and a single-letter heading from DIRECTIONS.
            self.x = 0
            self.y = 0
            self.facing = "N"
    
        def turn_left(self) -> None:
            # In Python, (-1) % 4 evaluates to 3, so stepping back from index 0 ("N")
            # wraps cleanly to index 3 ("W") without needing a special-case branch.
            current_index = DIRECTIONS.index(self.facing)
            next_index = (current_index - 1) % 4
            self.facing = DIRECTIONS[next_index]
    
        def turn_right(self) -> None:
            # Stepping forward from index 3 ("W") wraps via 4 % 4 == 0 back to "N".
            current_index = DIRECTIONS.index(self.facing)
            next_index = (current_index + 1) % 4
            self.facing = DIRECTIONS[next_index]
    
        def cell_ahead(self) -> Tuple[int, int]:
            # Compute the destination cell WITHOUT mutating self.x or self.y,
            # so the controller can check for collisions before moving the rover.
            dx, dy = STEPS[self.facing]
            return (self.x + dx, self.y + dy)
    
        def move_to(self, cell: Tuple[int, int]) -> None:
            self.x, self.y = cell
    
        def state(self) -> Tuple[int, int, str]:
            return (self.x, self.y, self.facing)
    
    
    class RoverController:
        """Runs text commands, one per line, and returns one report line per command.
    
        Commands (keywords are case-insensitive, ids are case-sensitive; text after '#' is a comment):
            CREATE <id>   new rover at (0, 0) facing N; does not change the selection
            DELETE <id>   remove a rover; deleting the selected rover clears the selection
            SELECT <id>   make <id> the active rover
            L | R | M     turn left, turn right, move forward (the selected rover)
    
        Report: "OK <state>" or "ERROR <code> <state>", where <state> is "<id> <x> <y> <dir>"
        for the selected rover, or "-" when no rover is selected. A failed command changes nothing.
        Error codes: unknown_command, bad_arguments, duplicate_id, no_such_rover,
        no_selection, blocked.
        """
    
        def __init__(self) -> None:
            # self.rovers: maps case-sensitive rover_id -> Rover instance, e.g. {"a": Rover()}
            self.rovers: Dict[str, Rover] = {}
            # self.selected: id of the currently active rover (e.g. "a"), or None when none is active
            self.selected: Optional[str] = None
    
        def execute(self, line: str) -> str:
            # Phase 1: tokenize the command line after stripping any '#' comment.
            words = split_command(line)
            if not words:
                return self._report("unknown_command")
    
            # Normalize the command keyword to uppercase while keeping rover IDs case-sensitive.
            command_name = words[0].upper()
            args = words[1:]
    
            # Phase 2: validate argument counts and dispatch management commands.
            if command_name in ("CREATE", "DELETE", "SELECT"):
                if len(args) != 1:
                    return self._report("bad_arguments")
                rover_id = args[0]
                if command_name == "CREATE":
                    error_code = self._create(rover_id)
                elif command_name == "DELETE":
                    error_code = self._delete(rover_id)
                else:
                    error_code = self._select(rover_id)
                return self._report(error_code)
    
            # Phase 3: validate argument counts and dispatch movement/turn commands.
            if command_name in ("L", "R", "M"):
                if len(args) != 0:
                    return self._report("bad_arguments")
                error_code = self._drive(command_name)
                return self._report(error_code)
    
            return self._report("unknown_command")
    
        def run(self, lines: Iterable[str]) -> List[str]:
            """Execute every non-blank line; blank and comment-only lines produce no report."""
            reports: List[str] = []
            for line in lines:
                # Skip blank lines and comment-only lines when running a multi-line script.
                if split_command(line):
                    reports.append(self.execute(line))
            return reports
    
        # Every helper below validates all preconditions BEFORE mutating state,
        # returning None on success or an error string on failure.
    
        def _create(self, rover_id: str) -> Optional[str]:
            if rover_id in self.rovers:
                return "duplicate_id"
            # Multiple newly created rovers may share (0, 0); collisions apply only to 'M' moves.
            self.rovers[rover_id] = Rover()
            return None
    
        def _delete(self, rover_id: str) -> Optional[str]:
            if rover_id not in self.rovers:
                return "no_such_rover"
            del self.rovers[rover_id]
            # Clear selection if we just deleted the active rover, preventing a dangling ID.
            if self.selected == rover_id:
                self.selected = None
            return None
    
        def _select(self, rover_id: str) -> Optional[str]:
            if rover_id not in self.rovers:
                return "no_such_rover"
            self.selected = rover_id
            return None
    
        def _drive(self, command_name: str) -> Optional[str]:
            if self.selected is None:
                return "no_selection"
            rover = self.rovers[self.selected]
            if command_name == "L":
                rover.turn_left()
            elif command_name == "R":
                rover.turn_right()
            else:
                # Look ahead before moving so a blocked move leaves the rover completely untouched.
                target_cell = rover.cell_ahead()
                if self._occupied_by_other(target_cell, self.selected):
                    return "blocked"
                rover.move_to(target_cell)
            return None
    
        def _occupied_by_other(self, cell: Tuple[int, int], moving_rover_id: str) -> bool:
            # Check every other existing rover's coordinates; scanning self.rovers handles
            # multiple rovers stacked at (0, 0) without needing a separate cell-count map.
            for other_id, other_rover in self.rovers.items():
                if other_id != moving_rover_id and (other_rover.x, other_rover.y) == cell:
                    return True
            return False
    
        def _report(self, error_code: Optional[str]) -> str:
            # Every command reports the currently selected rover's state, or "-" if none is selected.
            if self.selected is None:
                state_text = "-"
            else:
                x, y, facing = self.rovers[self.selected].state()
                state_text = f"{self.selected} {x} {y} {facing}"
    
            if error_code is None:
                return f"OK {state_text}"
            return f"ERROR {error_code} {state_text}"
    
    
    def split_command(line: str) -> List[str]:
        """Words of a command line, with any '#' comment removed."""
        # Split at the first '#' only (maxsplit=1) so everything after '#' is ignored as a comment.
        without_comment = line.split("#", 1)[0]
        return without_comment.split()
    
    
    def main() -> None:
        controller = RoverController()
        for line in sys.stdin:
            if split_command(line):
                print(controller.execute(line), flush=True)
    
    
    if __name__ == "__main__":
        main()
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture RoverController as a ground-control switchboard managing named rovers across an open grid. The switchboard maintains a roster dictionary (self.rovers, mapping each ID string to its Rover instance) and an active channel dial (self.selected) pointing to whichever rover currently receives drive commands. Rotations (L, R) step around a 4-point clockwise compass list (["N", "E", "S", "W"]) using modular arithmetic (wrapping past list ends with the remainder operator %), while forward moves (M) inspect cell_ahead() before updating coordinates.

Naive solutions commonly mix input() and print() directly inside movement methods, move first and attempt to roll back on collision, or store occupied cells in a plain set of (x, y) tuples. Hardcoding print() inside state logic makes unit testing clumsy, and a plain set of occupied cells breaks whenever two rovers spawn at (0, 0): as soon as the first rover drives away and removes (0, 0) from the set, the controller forgets the second rover is still sitting at (0, 0)! Returning formatted report strings and checking cell_ahead() against self.rovers before mutating coordinates avoids every one of those bugs.

Trace a short collision sequence from Example 1 with rovers r1 and r2: 1. CREATE r1, SELECT r1, R, M moves r1 to (1, 0) facing E -> OK r1 1 0 E. 2. CREATE r2 spawns r2 at (0, 0, N) while r1 remains selected -> OK r1 1 0 E. 3. SELECT r2, R aims r2 East from (0, 0) -> OK r2 0 0 E. 4. M checks r2.cell_ahead() == (1, 0), sees r1 occupying (1, 0), leaves r2 at (0, 0, E), and returns ERROR blocked r2 0 0 E. 5. L, M turns r2 North and steps into the empty cell (0, 1) -> OK r2 0 1 N.

Complexity

  • Time:
    • CREATE, DELETE, SELECT, L, and R each run in O(1) average time (plus O(L) to tokenize a line of L characters), because hash-table lookups, insertions, deletions, and 4-element list index lookups all take constant time on average.
    • M runs in O(R) time for R existing rovers because _occupied_by_other scans self.rovers. Across C commands, worst-case runtime is O(C * R).
  • Space: O(R) auxiliary memory to store one Rover instance per active ID in self.rovers (run(lines) additionally returns an O(C) list of report strings, whereas streaming via main() uses O(1) extra memory per line).

Edge cases

  • Driving with self.selected is None: Issuing L, R, or M before selecting a rover (or after deleting the selected rover) returns ERROR no_selection -.
  • Deleting the active rover vs. another rover: Deleting self.selected resets self.selected to None; deleting a non-selected rover preserves the active selection.
  • Re-creating a deleted ID: After DELETE scout, calling CREATE scout spawns a fresh rover at (0, 0, N).
  • Multiple rovers stacked at (0, 0): CREATE never fails on cell occupancy; any rover still parked at (0, 0) blocks another rover from moving back onto (0, 0).
  • Blocked moves vs. in-place turns: A blocked M returns ERROR blocked with (x, y, facing) untouched, whereas L and R rotate in place without occupancy checks.
  • Negative and large coordinates: Python's arbitrary-precision integers handle negative and distant coordinates without overflow or boundary branches.
  • Malformed lines, # comments, and casing: Empty strings passed to execute(""), extra arguments (M 3, CREATE a b), unknown tokens (LL), and inline # comments are all handled cleanly; keywords are case-insensitive while IDs are case-sensitive (x vs. X).

Common mistakes

  • Calling print() inside Rover or RoverController: Forces unit tests to capture sys.stdout instead of asserting directly on returned strings.
  • Using a set of occupied (x, y) coordinates: Breaks when two rovers start at (0, 0) and one moves away, falsely marking (0, 0) empty while the second rover remains there.
  • Mutating coordinates before checking collisions: Updating x, y first and undoing on error is brittle compared to checking cell_ahead() up front.
  • Forgetting to clear self.selected on DELETE: Leaves a dangling ID that raises KeyError on the next command or _report call.
  • Maintaining separate LEFT_OF and RIGHT_OF lookup maps: Invites copy-paste errors that (index ± 1) % 4 on ["N", "E", "S", "W"] avoids by construction.

Follow-up questions

  • How can you reduce the forward-move collision check from O(R) to O(1) time when thousands of rovers are active? Maintain a reference-counted dictionary cell_counts: Dict[Tuple[int, int], int] mapping each occupied (x, y) cell to the number of rovers currently on it. Increment cell_counts[(0, 0)] on CREATE, decrement (and remove when zero) on DELETE, and update the old and new cells on a successful M. Checking cell_counts.get(target_cell, 0) > 0 runs in O(1) average time while still handling multiple newly created rovers stacked at (0, 0).
  • What changes if the controller also needs to accept compact multi-step strings such as LMLMRM on one line? Add either a dedicated RUN <steps> command or recognize tokens composed solely of L, R, and M, invoking _drive step by step and emitting one status line per letter. Confirm with the interviewer whether a blocked move aborts the remaining steps in the string or skips only the blocked move; aborting on the first collision is usually safer for robotic control.
  • How would you extend the design to enforce rectangular map boundaries and static terrain obstacles? Accept optional grid bounds (min_x, max_x, min_y, max_y) and an obstacles: Set[Tuple[int, int]] set in RoverController.__init__. Inside _drive, after computing target_cell = rover.cell_ahead(), check map bounds first (out_of_bounds), static obstacles second (blocked), and other rovers third (blocked) before calling rover.move_to(target_cell) — leaving Rover itself completely unchanged.

Alternative approaches

  • 2D unit-vector or complex-number rotation: Store heading directly as (dx, dy) where turning left maps (dx, dy) -> (-dy, dx) and turning right maps (dx, dy) -> (dy, -dx) (equivalent to multiplying a complex heading by +i or -i). Indexing the 4-element DIRECTIONS ring is slightly more explicit and beginner-friendly when formatting single-letter compass strings.

Follow-up questions

Similar questions

More Shopify interview questions

All 63 Shopify questions →