Robot in a Tunnel
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2022-06-16
Problem Statement
Designing a system to navigate a robot through a straight or curved tunnel using a limited set of movement APIs. The tunnel has no T-junctions or intersections, so the robot only needs to move forward or turn to follow the path until it reaches the end.
The problem focuses on OOP design, API usage, and simulation logic.
Functional Requirements
1.Robot Movement APIs
•moveForward() → Moves the robot one unit forward in the current direction.
•turnLeft() → Rotates the robot 90° left (no movement).
•turnRight() → Rotates the robot 90° right (no movement).
2.Navigation
•The robot should be able to navigate through the tunnel until it reaches the end point.
•The tunnel may have turns but no T-junctions or branches.
•The robot should avoid hitting walls (tunnel boundaries).
3.Simulation / State Tracking
•Keep track of the robot’s current position (x, y) and direction (North, South, East, West).
•Provide a method to check whether the robot has reached the tunnel’s end.
4.Optional Enhancements
•Count number of moves taken.
•Support dynamic tunnels (can change shape).
Non-Functional Requirements
•Extensibility: Easy to support more complex tunnels in the future.
•Thread Safety: If simulating multiple robots concurrently.
•Testability: Clear APIs to allow unit testing and simulation.
Edge Cases & Constraints
•The robot starts at the tunnel entrance with a fixed initial direction.
•Tunnel walls are boundaries; robot should not go out of bounds.
•No T-junctions or branching paths → simplifies movement logic.
•Tunnel may have curves, so robot must correctly turn and follow the path.
Design Hints
•Key Classes / Interfaces:
•Robot → maintains position, direction, exposes APIs (moveForward, turnLeft, turnRight).
•Tunnel → represents the tunnel layout (grid/map, or abstract path).
•Simulator → orchestrates robot navigation using the APIs.
•Position → utility class to represent (x, y) coordinates.
•Direction → enum for NORTH, EAST, SOUTH, WEST.
•Design Patterns:
•Command Pattern → encapsulate robot actions as commands for simulation/testing.
•State Pattern → maintain robot’s current state (position + direction).
Example Flow
1.Initialize robot at (0,0) facing North.
2.Tunnel is represented as a 2D path or sequence of coordinates.
3.Simulator executes:
•If path ahead is free → moveForward()
•If path turns left → turnLeft(), then moveForward()
•If path turns right → turnRight(), then moveForward()
4.Continue until robot reaches the tunnel’s end.
Evaluation Areas
•Clean class design and API modeling.
•Correct handling of direction, position, and movement logic.
•Simulation loop and edge case handling (e.g., boundary checks).
•Extensibility to support more complex tunnels later.