Fleet Command Console for Grid-Walking Robots
Data Structure DesignModel answerLast updated
Design a text-driven controller that manages several robots on an unbounded grid, handling turns, steps, selection, error cases and cell collisions.
Fleet Command Console
Build a small text-driven console that controls robots moving on an infinite 2D grid. Build it in three stages, each extending the previous one.
Stage 1: one robot
A robot starts at (0, 0) facing North. It understands three commands:
L: rotate 90 degrees counter-clockwise (N -> W -> S -> E -> N)R: rotate 90 degrees clockwise (N -> E -> S -> W -> N)M: advance one cell in the direction it faces
After every command, print the robot's current position and heading.
Stage 2: several robots
Add commands to manage a fleet:
CREATE <id>: add a new robot in the default state (0, 0, N)DELETE <id>: remove a robotSELECT <id>: make that robot the active oneL,R,Mact on the active robot only
Decide and document what happens on invalid operations, for example selecting or deleting an id that does not exist, creating a duplicate id, or sending L/R/M when nothing is selected.
Stage 3: no collisions
If the active robot issues M and the cell it would enter is occupied by another robot, the move fails and the robot keeps its position and heading. The console must still print the state after the command, along with a status or error message of your choosing.
What you must specify
You choose the exact I/O format (a REPL or lines read from stdin), but it has to be unambiguous and testable. State clearly:
- the accepted command syntax,
- what is printed after each command (position, heading, and optionally a status),
- your policy for each invalid operation.
Rules
- The grid is unbounded, so coordinates can be negative.
- Robot ids are unique strings.
- Keep the design clean and unit-testable, and include tests.
Sample session
CREATE a
SELECT a
M
R
M
CREATE b
SELECT b
M
SELECT a
M # fails if b occupies the target cell
Your printed format may differ from any particular one, but it must show position and heading after every command.
Expected: a short design explanation, the implementation, its complexity, and a few tests.
Hints
Hint 1
Represent a robot as (x, y, heading). Keep headings in the order N, E, S, W so that R is +1 and L is -1 modulo 4, and store a direction-to-offset table for moving.
Hint 2
Put all logic in one method that takes a command string and returns the output string. The controller holds a dict from id to robot plus the currently selected id. This lets you unit test without stdin.
Hint 3
For collision checks, keep a second dict from (x, y) to robot id that always mirrors robot positions. Compute the target cell, check it before changing anything, and update the index on create, delete and each successful move. Decide what happens when CREATE is issued while (0, 0) is occupied.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task has three layers, and a good design lets each one slot in without rewrites.
- Robot state is a tiny value:
(x, y, heading). Turning is modular arithmetic over the ordered string"NESW". Moving adds a heading-specific offset. - The controller owns a registry
id -> robotand aselectedid. Every command passes through oneexecute(line) -> outputmethod. Because it is string-in, string-out, tests never touch stdin. - Collision avoidance needs an occupancy index
(x, y) -> id. Scanning every robot on eachMcosts O(n). A dict makes the check O(1). The invariant is that the index always mirrors robot positions, so it is updated on create, delete and every successful move.
Define the I/O contract first
Pinning this down before coding is what makes the solution testable.
- Input: one command per line. Valid forms:
CREATE <id>,DELETE <id>,SELECT <id>,L,R,M. Case-sensitive. Blank lines are skipped, and text after#is a comment. - Output: exactly one line per command:
STATUS | STATE.STATUSisOKorERROR <CODE>.STATEis<id> <x> <y> <heading>for the active robot, orNONEif nothing is selected.
Invalid-operation policies
State these choices explicitly:
| Situation | Behavior |
|---|---|
Duplicate CREATE | ERROR DUPLICATE_ID; existing robot untouched |
SELECT/DELETE unknown id | ERROR NO_SUCH_ROVER; selection unchanged |
| Delete the active robot | succeeds and clears the selection |
L/R/M with nothing selected | ERROR NO_ROVER_SELECTED |
Blocked M | ERROR BLOCKED; position and heading unchanged |
CREATE while (0,0) is occupied | ERROR ORIGIN_OCCUPIED |
| Wrong argument count | ERROR BAD_ARGS |
| Unknown verb | ERROR UNKNOWN_COMMAND |
CREATE | does not auto-select |
The ORIGIN_OCCUPIED rule is a trade-off. Without it two robots could share a cell, which breaks the one-robot-per-cell invariant the occupancy index depends on. The alternative is to allow stacking and only police moves, which is simpler but weaker. Mention both.
Why it is correct
- Turning: with
DIRS = "NESW",Ris(i+1) % 4andLis(i-1) % 4, giving exactly N->E->S->W and N->W->S->E. Python's modulo keeps the result non-negative. - Moving: compute the target, check occupancy, and only then mutate. A failed move therefore leaves no partial state. On success, remove the old index entry, set the new position, and insert the new entry.
- Errors: raise a domain exception inside dispatch and catch it in
execute. Every command yields exactly one output line, and state is reported even on failure.
Complexity
- Time: O(1) average per command (dict operations), plus parsing linear in line length.
- Space: O(R) for R live robots.
Edge cases
- Negative coordinates work naturally with plain integers.
- A robot never blocks itself: its own cell is never its target.
- Deleting a robot frees its cell immediately, so a previously blocked move can then succeed.
- A deleted id can be created again and starts fresh at (0, 0, N).
M xor a bareCREATEisBAD_ARGS.
Code
import sys
import unittest
from dataclasses import dataclass
DIRS = "NESW"
DELTA = {"N": (0, 1), "E": (1, 0), "S": (0, -1), "W": (-1, 0)}
@dataclass
class Rover:
x: int = 0
y: int = 0
d: str = "N"
def turn(self, cmd):
step = 1 if cmd == "R" else -1
self.d = DIRS[(DIRS.index(self.d) + step) % 4]
def ahead(self):
dx, dy = DELTA[self.d]
return (self.x + dx, self.y + dy)
class RoverError(Exception):
pass
class Controller:
def __init__(self):
self.rovers = {}
self.occupied = {}
self.selected = None
def execute(self, line):
line = line.split("#", 1)[0].strip()
if not line:
return None
try:
self._dispatch(line.split())
status = "OK"
except RoverError as e:
status = f"ERROR {e}"
return f"{status} | {self._state()}"
def _dispatch(self, tokens):
cmd, args = tokens[0], tokens[1:]
if cmd in ("CREATE", "DELETE", "SELECT"):
if len(args) != 1:
raise RoverError("BAD_ARGS")
getattr(self, "_" + cmd.lower())(args[0])
elif cmd in ("L", "R", "M"):
if args:
raise RoverError("BAD_ARGS")
rover = self._current()
if cmd == "M":
self._move(rover)
else:
rover.turn(cmd)
else:
raise RoverError("UNKNOWN_COMMAND")
def _create(self, rid):
if rid in self.rovers:
raise RoverError("DUPLICATE_ID")
if (0, 0) in self.occupied:
raise RoverError("ORIGIN_OCCUPIED")
self.rovers[rid] = Rover()
self.occupied[(0, 0)] = rid
def _delete(self, rid):
rover = self.rovers.pop(rid, None)
if rover is None:
raise RoverError("NO_SUCH_ROVER")
del self.occupied[(rover.x, rover.y)]
if self.selected == rid:
self.selected = None
def _select(self, rid):
if rid not in self.rovers:
raise RoverError("NO_SUCH_ROVER")
self.selected = rid
def _current(self):
if self.selected is None:
raise RoverError("NO_ROVER_SELECTED")
return self.rovers[self.selected]
def _move(self, rover):
target = rover.ahead()
if target in self.occupied:
raise RoverError("BLOCKED")
del self.occupied[(rover.x, rover.y)]
rover.x, rover.y = target
self.occupied[target] = self.selected
def _state(self):
if self.selected is None:
return "NONE"
r = self.rovers[self.selected]
return f"{self.selected} {r.x} {r.y} {r.d}"
def main():
ctl = Controller()
for line in sys.stdin:
out = ctl.execute(line)
if out is not None:
print(out, flush=True)
class ControllerTest(unittest.TestCase):
def run_cmds(self, *cmds):
c = Controller()
return [c.execute(x) for x in cmds]
def test_basic_walk(self):
out = self.run_cmds("CREATE a", "SELECT a", "M", "R", "M")
self.assertEqual(out[-1], "OK | a 1 1 E")
def test_left_from_north(self):
out = self.run_cmds("CREATE a", "SELECT a", "L", "M")
self.assertEqual(out[-1], "OK | a -1 0 W")
def test_no_selection(self):
out = self.run_cmds("M")
self.assertEqual(out[0], "ERROR NO_ROVER_SELECTED | NONE")
def test_collision(self):
c = Controller()
for cmd in ["CREATE a", "SELECT a", "M", "R", "M",
"L", "L", "M"]: # a is now at (0,1)
c.execute(cmd)
c.execute("DELETE a")
c.execute("CREATE b")
c.execute("SELECT b")
c.execute("M") # b at (0,1)
c.execute("CREATE c") # (0,0) free again
c.execute("SELECT c")
out = c.execute("M") # target (0,1) occupied
self.assertTrue(out.startswith("ERROR BLOCKED"))
self.assertIn("c 0 0 N", out)
def test_delete_frees_cell(self):
c = Controller()
for cmd in ["CREATE a", "SELECT a", "M", "CREATE b", "SELECT b", "M"]:
c.execute(cmd)
self.assertTrue(c.execute("M").startswith("ERROR BLOCKED") is False)
if __name__ == "__main__":
main()
Common mistakes
- Scanning all robots on every move instead of keeping an occupancy index.
- Mutating position before the collision check, leaving the index stale on failure.
- Forgetting to clear the selection when the active robot is deleted.
- Letting two robots start on the same cell without deciding how that interacts with collisions.
- Mixing I/O into the logic so nothing can be unit tested.