Modeling a Multi-Car Lift Dispatcher with Swappable Policies
Data Structure DesignModel answerLast updated
Design an object-oriented lift (elevator) control system: classes, per-car state machine, stop ordering, pluggable dispatch, edge cases, and testable core logic.
You are asked to design the control software for a lift (elevator) system in a building, using object-oriented principles. Explain your class model, then show how a single button press ends with a car stopping at the requested floor, and write the core control logic in TypeScript or another language you prefer.
Baseline setup (confirm or adjust, then state your defaults):
- The building has floors from a lowest to a highest number and one or more cars.
- Every floor has hall buttons for up and down. The bottom floor only has up, and the top floor only has down.
- Every car has an internal panel of floor buttons.
- A central controller chooses which car serves each hall call. A car moves one floor per step, stops, and opens its doors.
Constraints:
- Model the physical world as a step-based simulation (a
tick()orstep()call) so the logic can be tested with no hardware and no real clock. - Scheduling goals, special modes, and capacity rules are not fixed. Pick defaults and say what they are.
Questions you should consider asking:
- How many floors and cars must be supported? Should it work with one car as well as a group?
- What is being optimized: waiting time, total travel time, or energy?
- Are there weight or capacity limits, and what happens when a car is full?
- Which special modes matter (maintenance, emergency stop, fire service)?
- What happens to requests already assigned to a car that goes out of service?
Expected in your answer:
- Requirements and scope.
- Classes and their responsibilities.
- A car state model with valid transitions.
- A stop-ordering policy within a car and a separately swappable car-assignment policy.
- Edge cases: duplicate presses, a request for the current floor, invalid floors, and a car failing while holding requests.
- Code for the core logic, plus a note on extensibility and testing.
Hints
Hint 1
Separate three concerns: who decides which car answers a call (dispatcher), how one car orders its own stops (car), and how input arrives (button panels producing request objects).
Hint 2
Give each car an explicit state (idle, moving up, moving down, doors open, out of service) and keep two sorted sets of pending stops, one for floors above and one for floors below. Keep the current direction until nothing remains ahead, then reverse.
Hint 3
Make the assignment policy an interface so you can swap nearest-car for something smarter, and drive everything through a step function so tests can assert exact floor sequences. Decide up front what happens to duplicates and to a request for the floor the car is already at.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and scope
In scope: N floors (minFloor..maxFloor), M cars (M ≥ 1), hall calls (floor + direction), car calls (destination floor), step-based simulation.
Defaults I would state:
- Goal: minimize average waiting time, with fairness as a secondary concern.
- No weight limit modeled initially, but a
isFull()hook exists on the car so the dispatcher can skip full cars. - Modes: normal and out-of-service only. Fire service and maintenance are extensions.
- Doors stay open for a fixed number of ticks.
Out of scope: real motor physics, door sensors, hardware drivers.
2. Classes and responsibilities
| Class | Responsibility |
|---|---|
ElevatorSystem (controller) | Entry point. Receives hall calls, asks the dispatch policy for a car, forwards the request, and advances all cars on each tick. |
Car | Owns its floor, direction, state, door timer and pending stops. Decides its next move. |
Request / HallCall | Immutable value: floor and direction. A car call is just a destination floor. |
Direction | Enum: UP, DOWN, NONE. |
CarState | Enum: IDLE, MOVING_UP, MOVING_DOWN, DOORS_OPEN, OUT_OF_SERVICE. |
DispatchPolicy (interface) | pick(cars, call): Car | null. Swappable strategy. |
ButtonPanel | Input source (hall or in-car). Validates the floor and emits requests to the system or car. |
3. Car state model
IDLE→MOVING_UP/MOVING_DOWNwhen a stop is added above or below.IDLE→DOORS_OPENwhen a request is for the current floor.MOVING_*→DOORS_OPENwhen the car reaches a floor that is a pending stop.DOORS_OPEN→MOVING_*after the timer expires and stops remain; otherwise →IDLE.- Any state →
OUT_OF_SERVICEon fault;OUT_OF_SERVICE→IDLEon recovery.
Invalid: moving directly from MOVING_UP to MOVING_DOWN. A car must stop (or run out of upward stops) first.
4. Policies
Within a car (SCAN / "elevator algorithm"): keep the direction while any pending stop lies ahead. Serve stops in floor order along that direction, then reverse. Implement with two sorted sets: upStops (floors above) and downStops (floors below), relative to the current floor. This avoids starvation and minimizes direction changes.
Hall-call assignment (Strategy):
NearestCarPolicy: score each in-service car by a cost, such as distance if idle or moving toward the call in the same direction, or distance to the end of the sweep plus the way back otherwise. Pick the lowest cost.- Later options: least-loaded, zoned, or destination dispatch. Swapping them requires no change to
CarorElevatorSystem.
5. Core code (TypeScript)
enum Direction { UP, DOWN, NONE }
enum CarState { IDLE, MOVING_UP, MOVING_DOWN, DOORS_OPEN, OUT_OF_SERVICE }
interface HallCall { floor: number; dir: Direction }
class Car {
state = CarState.IDLE;
private stops = new Set<number>();
private doorTicks = 0;
constructor(public id: number, public floor: number,
private min: number, private max: number,
private doorTime = 2) {}
addStop(f: number): void {
if (f < this.min || f > this.max) throw new RangeError("bad floor");
if (this.state === CarState.OUT_OF_SERVICE) return;
if (f === this.floor && this.state !== CarState.MOVING_UP
&& this.state !== CarState.MOVING_DOWN) {
this.openDoors(); return;
}
this.stops.add(f); // Set ignores duplicates
}
pending(): number[] { return [...this.stops]; }
fail(): number[] {
const orphaned = this.pending();
this.stops.clear();
this.state = CarState.OUT_OF_SERVICE;
return orphaned;
}
recover(): void {
if (this.state === CarState.OUT_OF_SERVICE) this.state = CarState.IDLE;
}
private openDoors() { this.state = CarState.DOORS_OPEN; this.doorTicks = this.doorTime; }
private heading(): Direction {
const above = [...this.stops].some(s => s > this.floor);
const below = [...this.stops].some(s => s < this.floor);
if (this.state === CarState.MOVING_UP && above) return Direction.UP;
if (this.state === CarState.MOVING_DOWN && below) return Direction.DOWN;
if (above) return Direction.UP;
if (below) return Direction.DOWN;
return Direction.NONE;
}
tick(): void {
if (this.state === CarState.OUT_OF_SERVICE) return;
if (this.state === CarState.DOORS_OPEN) {
if (--this.doorTicks > 0) return;
this.state = CarState.IDLE;
}
const d = this.heading();
if (d === Direction.NONE) { this.state = CarState.IDLE; return; }
this.floor += d === Direction.UP ? 1 : -1;
this.state = d === Direction.UP ? CarState.MOVING_UP : CarState.MOVING_DOWN;
if (this.stops.delete(this.floor)) this.openDoors();
}
}
interface DispatchPolicy { pick(cars: Car[], call: HallCall): Car | null }
class NearestCarPolicy implements DispatchPolicy {
pick(cars: Car[], call: HallCall): Car | null {
let best: Car | null = null, bestCost = Infinity;
for (const c of cars) {
if (c.state === CarState.OUT_OF_SERVICE) continue;
const cost = Math.abs(c.floor - call.floor) + c.pending().length;
if (cost < bestCost) { bestCost = cost; best = c; }
}
return best;
}
}
class ElevatorSystem {
private unassigned: HallCall[] = [];
constructor(private cars: Car[], private policy: DispatchPolicy) {}
hallCall(call: HallCall): void {
const car = this.policy.pick(this.cars, call);
if (car) car.addStop(call.floor); else this.unassigned.push(call);
}
carCall(carId: number, floor: number): void {
this.cars[carId].addStop(floor);
}
failCar(id: number): void {
for (const f of this.cars[id].fail()) this.hallCall({ floor: f, dir: Direction.NONE });
}
tick(): void {
this.unassigned = this.unassigned.filter(c => (this.hallCall(c), false));
this.cars.forEach(c => c.tick());
}
}
The sketch tracks only floors for hall calls. A fuller version stores the call direction with each stop so a car sweeping up does not pick up a down-call passenger prematurely.
6. Edge cases
- Duplicate presses: a
Setof stops makes them idempotent. - Request for the current floor: open the doors immediately if the car is not mid-move.
- Invalid floor: reject at the panel and again in
Car. - Car failure: clear its stops and reassign them through the dispatcher. If no car is available, queue them until one recovers.
- Boundary buttons: no up button on the top floor and no down button on the bottom floor, enforced by the panel.
- Full car: the policy skips it for hall calls, while in-car stops continue.
7. Complexity
Each tick is O(M · S) in this simple version (S = pending stops per car). Using sorted sets for upStops and downStops gives O(log S) per insert and O(log S) for next-stop lookup. Dispatch is O(M) per call.
8. Testability and extension
- No wall clock: tests call
tick()and assert the sequence of floors and states, such as "car at 1 with stops {3,5} visits 2,3(open),4,5(open)". - Inject the policy so dispatch can be unit-tested with fake cars.
- Extensions: fire mode (an overriding state that clears stops and returns to the lobby), capacity, destination dispatch, and zoning for tall buildings.
Common mistakes
- Putting scheduling logic inside the button classes.
- No explicit state model, leading to cars that reverse mid-travel.
- Forgetting orphaned requests when a car fails.
- Hard-coding a single dispatch rule instead of an interface.
- Ignoring direction of hall calls, so a car picks up passengers going the opposite way.