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:
-
Single-rover state (
Rover)- Every rover spawns at
(x=0, y=0)withfacing="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 inself.facingwithout mutating the rover.move_to(cell)updates(self.x, self.y)tocell, andstate()returns(self.x, self.y, self.facing).
- Every rover spawns at
-
Comment stripping (
split_command(line) -> List[str])- Strips everything from the first
#character to the end oflineand returns the whitespace-separated tokens that remain.
- Strips everything from the first
-
Fleet management, collision blocking, and reporting (
RoverController)- Command keywords are case-insensitive (
selectandSELECTare equivalent), while rover<id>tokens are case-sensitive (r1andR1are distinct):CREATE <id>: adds a new rover<id>at(0, 0)facing"N"without changingself.selected. Fails withduplicate_idif<id>already exists. Newly created rovers may coexist at(0, 0).DELETE <id>: removes<id>fromself.rovers; ifself.selected == <id>, resetsself.selectedtoNone. Fails withno_such_roverif<id>is absent.SELECT <id>: setsself.selected = <id>. Fails withno_such_roverif<id>is absent.L,R,M: turns left, turns right, or advances the selected rover one step forward. Fails withno_selectionwhenself.selectedisNone. ExecutingMfails withblockedwhenever another existing rover occupiescell_ahead(), leaving the active rover's coordinates and heading unchanged.
- Argument & command checks:
CREATE,DELETE, andSELECTrequire exactly1argument (bad_argumentsotherwise);L,R, andMtake0arguments (bad_argumentsotherwise). Any other command name — or an empty/comment-only string passed directly toexecute(line)— fails withunknown_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>"forself.selected, or"-"whenself.selectedisNone. - Batch execution:
run(lines)skips blank and comment-only lines, callsexecuteon each remaining line in order, and returns the list of report strings.
- Command keywords are case-insensitive (
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 toCREATE,L, orR.
Step-by-step walkthrough
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 r1andSELECT r1both work), while rover IDs are case-sensitive tokens without whitespace (r1andR1are distinct rovers). Everything from#through the end of a line is stripped as an inline comment, allowing annotated lines likeM # blocked by r1 at (1, 0)to execute cleanly. - Output format: every executed command produces one space-delimited report string:
OK <state>on success, orERROR <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, andblocked. - State invariants (rules that always hold):
- A failed command never modifies any rover or
self.selected. CREATE <id>spawns a rover at(0, 0)facingNwithout changingself.selected.- Deleting the currently selected rover resets
self.selectedback toNone. - Multiple newly created rovers may coexist at
(0, 0); collision blocking applies specifically when executingM.
- A failed command never modifies any rover or
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- Input syntax: one command per line. Command keywords (
Model a single rover on the 2D grid
Keep the
Roverclass 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/elifchains for left and right rotations, store the four compass headings clockwise inDIRECTIONS = ["N", "E", "S", "W"]. Turning right steps+1around this list, turning left steps-1, and% 4(modulo 4) wraps around both ends automatically. Because(-1) % 4 == 3in Python, turning left from"N"(index0) lands directly on"W"(index3).Splitting movement into
cell_ahead()(computing the next square without mutatingself.xorself.y) andmove_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)Manage multiple rovers and active selection
RoverControllertracks the fleet with two fields: 1.self.rovers: dictionary mapping eachrover_idstring to itsRoverobject. 2.self.selected: ID string of the active rover, orNonewhen none is selected.Each lifecycle helper (
_create,_delete,_select) checks preconditions before mutating state, returningNoneon success or an error code string on failure. In_delete, remember to clearself.selected = Nonewhenever the deleted rover was the active one — otherwise the next command or status report would crash withKeyError.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 NoneAdd look-ahead collision avoidance
When
L,R, orMruns,_drivefirst checksself.selected is not None. Rotations (LandR) spin in place and never collide.For
M, we querytarget_cell = rover.cell_ahead()and scanself.roversto check whether any other rover already occupiestarget_cell. Why scanself.roversinstead of keeping a plain Pythonsetof occupied coordinates? Because two newly created roversr1andr2both start at(0, 0). Ifr1drove away and deleted(0, 0)from a plainset, the controller would forget thatr2is still parked at(0, 0)! Readingself.roversdirectly 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 Efrom 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 FalseParse lines, dispatch commands, and format reports
Now connect raw input lines to the controller methods:
split_command(line)removes any#comment vialine.split("#", 1)[0]and splits remaining whitespace-delimited words.execute(line)validates argument counts (1argument forCREATE/DELETE/SELECT,0arguments forL/R/M) so malformed lines likeCREATE a b,M 3, orLLreturn clean error reports._report(error_code)formats<id> <x> <y> <dir>forself.selected(or-whenNone) and prependsOKorERROR <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}"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 NWhen
r2faces East at(0, 0),r2.cell_ahead()is(1, 0), whichr1already occupies — soexecutereturnsERROR blocked r2 0 0 Ewithout changingr2's state. Turning left to"N"aimsr2at the empty cell(0, 1), so the finalMsucceeds.Assemble the complete solution
Combining
Rover,RoverController,split_command, and thesys.stdinrunner 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, andReach run in O(1) average time (plus O(L) to tokenize a line ofLcharacters), because hash-table lookups, insertions, deletions, and 4-element list index lookups all take constant time on average.Mruns in O(R) time forRexisting rovers because_occupied_by_otherscansself.rovers. AcrossCcommands, worst-case runtime is O(C * R).
- Space: O(R) auxiliary memory to store one
Roverinstance per active ID inself.rovers(run(lines)additionally returns an O(C) list of report strings, whereas streaming viamain()uses O(1) extra memory per line).
Edge cases
- Driving with
self.selected is None: IssuingL,R, orMbefore selecting a rover (or after deleting the selected rover) returnsERROR no_selection -. - Deleting the active rover vs. another rover: Deleting
self.selectedresetsself.selectedtoNone; deleting a non-selected rover preserves the active selection. - Re-creating a deleted ID: After
DELETE scout, callingCREATE scoutspawns a fresh rover at(0, 0, N). - Multiple rovers stacked at
(0, 0):CREATEnever 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
MreturnsERROR blockedwith(x, y, facing)untouched, whereasLandRrotate 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 toexecute(""), 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 (xvs.X).
Common mistakes
- Calling
print()insideRoverorRoverController: Forces unit tests to capturesys.stdoutinstead of asserting directly on returned strings. - Using a
setof 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, yfirst and undoing on error is brittle compared to checkingcell_ahead()up front. - Forgetting to clear
self.selectedonDELETE: Leaves a dangling ID that raisesKeyErroron the next command or_reportcall. - Maintaining separate
LEFT_OFandRIGHT_OFlookup maps: Invites copy-paste errors that(index ± 1) % 4on["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. Incrementcell_counts[(0, 0)]onCREATE, decrement (and remove when zero) onDELETE, and update the old and new cells on a successfulM. Checkingcell_counts.get(target_cell, 0) > 0runs 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 ofL,R, andM, invoking_drivestep by step and emitting one status line per letter. Confirm with the interviewer whether ablockedmove 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 anobstacles: Set[Tuple[int, int]]set inRoverController.__init__. Inside_drive, after computingtarget_cell = rover.cell_ahead(), check map bounds first (out_of_bounds), static obstacles second (blocked), and other rovers third (blocked) before callingrover.move_to(target_cell)— leavingRoveritself 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+ior-i). Indexing the 4-elementDIRECTIONSring is slightly more explicit and beginner-friendly when formatting single-letter compass strings.
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?
- What changes if the controller also needs to accept compact multi-step strings such as LMLMRM on one line?
- How would you extend the design to enforce rectangular map boundaries and static terrain obstacles?
Similar questions
- Jaccard Overlap Score Between String Collections
- Set-Based Jaccard Similarity on String Lists
- Storefront Theme Tag Similarity
- Bounded Grid Robot Simulator
- Detect Copied Storefront Themes
- Thread-Safe Fixed-Size LRU Cache
More Shopify interview questions
- Grid Rover Navigation Simulator Easy
- In-Memory Bidirectional URL Shortener Medium
- Bounded LRU Cache and Gift Exchange Pairing Easy Pro
- Numeric Sequence and Grid Pattern Reasoning Easy Pro
- Rapid Mental Arithmetic and Numerical Bounds Medium Pro
- Measuring Unlicensed Theme Usage and Revenue Impact Medium Pro
- Product Data Scientist Recruiter Screen at Shopify Easy Pro
- Evaluating and Negotiating Values-Intensive Interview Loops Medium Pro
- Automated Order Refund Engine with Idempotent Payouts Medium Pro
- End-to-End Technical Project Walkthrough Easy Pro