"Design an elevator system" sounds like a drawing exercise. A weak answer draws an Elevator, a Floor, a Button and a Door, adds moveUp() and moveDown(), and stops. Nothing in that answer says which car comes when you press a button, or in what order a car visits the floors its riders asked for.
Those two questions are the design. An interviewer wants to hear how one controller hands each call to one car, how a car decides where to go next, and what the building does when presses arrive from every floor at once. They also want to know what happens to the people waiting for a car that breaks down.
This article walks through the question the way a 45 minute interview goes. We ask questions, find the classes, then build the design one decision at a time. Every snippet is cut from a complete Java project that compiles and runs. The Open file button on a snippet opens the whole file in a code browser, and the full project is at the end.
Ask before you design
The question is vague on purpose. Each question below changes the code, and the right-hand column says how.
| Question | What we assume | What it changes |
|---|---|---|
| How many floors and cars? | One building, floors 0 to 10, three cars | A FloorRange and a list of cars in one controller |
| Which buttons are there? | Up and down on each floor, except no up at the top and no down at the bottom. A panel of floors inside each car | Two kinds of request, and a check that a button exists |
| Who picks the car for a hall call? | One central controller | One class holds every car and decides |
| How does it pick? | The nearest car, counting the floors of its current run. The owner may want another rule | A dispatch rule behind an interface |
| When is the car picked? | As soon as the button is pressed, so a display can show which car is coming | Each hall call belongs to one car from the moment it lights, or waits in the queue until a car can take it |
| In what order does a car visit floors? | It keeps going one way while it has work in that direction, then turns | The stop logic inside each car |
| How do we deal with time? | In ticks. One tick moves a car one floor. A stop holds a car for a fixed number of ticks | A step() method instead of clocks and sleeps |
| Are presses concurrent? | Yes. Every floor and every car panel can press at once, while the timer ticks | The controller must be safe from many threads |
| Can a car break down? | Yes. It stops where it is, and its riders get out there | Its waiting callers must go to other cars |
| Capacity, fire mode, private floors? | Not in this version | Nothing yet. We come back to them at the end |
The question that changes the most is "when is the car picked?". If the controller picks a car at the moment of the press, every lit button belongs to exactly one car or waits in the queue until a car can take it. The design has to keep that true when cars break down and presses race each other.
Requirements
Functional:
- Pressing a hall button gives that call to one car in service, and says which car. Pressing a lit button again changes nothing.
- Pressing a floor inside a car adds that floor to the car's stops.
- Each car visits its stops in sweeps. It keeps going one way while it has stops in that direction, and picks up callers going the other way only where it turns round.
- A car that breaks down stops where it is. Its hall calls go to other cars. Its riders get out, so the floors they pressed are dropped.
- If no car is in service, a hall call waits and is given to the first car that returns.
Out of scope: capacity and overload, fire service mode, a floor that only some riders may reach, and choosing the destination before boarding. We come back to each of these at the end.
Everything lives in memory, as is normal for a low-level design interview.
What the code itself must handle:
- Many presses at once.
requestPickup,pressCarButtonandstepwill be called from different threads together. - Rules that change. The way a car is picked will change. Changing it should not mean editing the controller.
- Testable. A test must be able to say "after 7 ticks, car A is at floor 7" and check it, with no sleeping.
Finding the classes
We start from the nouns in the requirements. Most become classes. Some do not, and dropping them is part of the design.
Should a floor be a class?
A Floor class with its own buttons
A Floor class is tempting, because "floor" is in the question. It would hold its number and two buttons, and the buttons would call the controller. It has no behaviour of its own, so it adds a file and a layer between a press and the controller.
A floor is an int, and FloorRange says which floors existOur pick
Every place a floor appears, a number is enough. The one rule about floors, "the top floor has no up button", lives in one small record. If floors later need their own data, such as a floor that only some cars serve, a class can come then.
Data or behaviour?
Some things only carry data and never change once created: a hall call, a stop a car made, a snapshot of a car. In Java these are records: classes whose fields are fixed when they are created, with equals, hashCode and toString written for us.
public record HallCall(int floor, Direction direction) { public HallCall { Objects.requireNonNull(direction, "direction"); } @Override public String toString() { return floor + " " + direction; }}Records matter here for a practical reason. A HallCall is the key the controller uses to ask "is this button already lit?", and a record compares by value, so two presses of 7 DOWN make equal calls.
The class diagram
The classes fall into three groups:
- Data:
HallCall,Stop,CarStatus,FloorRange,Direction,CarStateandAssignment. These are records and enums, and one small class, becauseAssignmenthands back its car as anOptional. - The core:
ElevatorControllerandElevatorCar. They hold the changing state (where each car is and where it must go) and keep it correct under many threads. - The rule that changes:
DispatchStrategy, with two implementations, andCarView, the window through which a rule sees a car.
ElevatorCar is package-private. Code outside the elevator package cannot create a car or call the methods that change it. Everything goes through the controller, which is what lets one lock protect every car.
Building it
Floors, buttons and calls
A building has a lowest and a top floor, and the buttons at the two ends are missing. FloorRange holds that rule:
public record FloorRange(int lowest, int top) { // Far above any real building, and small enough that sums of floor distances never overflow an int. public static final int MAX_FLOORS = 1_000; public FloorRange { if (top <= lowest) { throw new IllegalArgumentException("The top floor must be above the lowest floor"); } if ((long) top - lowest >= MAX_FLOORS) { throw new IllegalArgumentException("A building can have at most " + MAX_FLOORS + " floors"); } } public boolean contains(int floor) { return floor >= lowest && floor <= top; } /** The top floor has no up button, and the lowest floor has no down button. */ public boolean hasButton(HallCall call) { if (!contains(call.floor())) { return false; } if (call.direction() == Direction.UP) { return call.floor() < top; } return call.floor() > lowest; }}The constructor also refuses a building of more than 1,000 floors. No real building comes close, and the cap means the sums of floor distances in the dispatch rule can never overflow an int. The controller asks hasButton before it accepts a press. A press of UP on floor 10 is a programmer error, because the panel on floor 10 has no such button, so it throws IllegalArgumentException. Every check in this design works the same way: a press that cannot exist throws, and everything a real person can do returns an answer. A rider who presses a floor in a car that is out of service gets false back, because a dead panel is something a real person can press.
One Request type, or hall calls and car calls apart?
One Request class with a type field
This looks tidy: one queue of requests. But the two behave differently. A hall call has a direction and must be given to a car. A car call has no direction and already belongs to the car it was pressed in. One class would carry a direction that car calls ignore, and every method would check the type first.
HallCall is a record; a car call is a floor in the car's own setOur pick
The controller deals with hall calls, because only it can choose a car. The car deals with car calls, because nobody else needs them. Each piece of data lives with the only code that uses it.
One car, one tick at a time
Each car keeps its own position and its own stops. Here are its fields:
final class ElevatorCar implements CarView { private final String id; private final int doorTicks; private int floor; private CarState state = CarState.IDLE; private Direction heading = Direction.UP; private int doorTicksLeft; // Floors the riders inside have pressed. private final TreeSet<Integer> carCalls = new TreeSet<>(); // Hall calls the controller has given this car, by the way the caller wants to go. private final TreeSet<Integer> upCalls = new TreeSet<>(); private final TreeSet<Integer> downCalls = new TreeSet<>();The car keeps three sorted sets. carCalls holds the floors its riders pressed. upCalls and downCalls hold the hall calls the controller gave it, split by the way each caller wants to go. A TreeSet keeps its floors in order, so "is there a stop above me?" is one call to higher(floor).
Time moves only when step() is called. Each call is one tick:
Optional<Stop> step(long tick) { if (state == CarState.OUT_OF_SERVICE) { return Optional.empty(); } if (state == CarState.DOORS_OPEN) { if (doorTicksLeft > 0) { doorTicksLeft--; return Optional.empty(); } state = CarState.IDLE; } return stopOrMove(tick); } private Optional<Stop> stopOrMove(long tick) { if (shouldStopHere()) { return Optional.of(openDoors(tick)); } Optional<Direction> next = nextDirection(); if (next.isEmpty()) { state = CarState.IDLE; return Optional.empty(); } heading = next.get(); floor += heading == Direction.UP ? 1 : -1; state = heading == Direction.UP ? CarState.MOVING_UP : CarState.MOVING_DOWN; if (shouldStopHere()) { return Optional.of(openDoors(tick)); } return Optional.empty(); }In one tick a car does one of three things. A car out of service does nothing. A car with its doors open counts down doorTicksLeft, and stays where it is until the count is used up. Any other car first checks whether it should open its doors where it is. If not, it picks a direction, moves one floor, and checks again.
A stop therefore holds a car for doorTicks ticks after the tick it arrives in. With doors set to 2 ticks, a car that stops once on the way reaches its last floor 2 ticks later than one that does not stop.
Real time, or ticks?
A thread per car that sleeps between floors
This is closer to how the hardware runs. But a test of "car A reaches floor 7" would have to sleep and hope the timing works out, and two cars on two threads would need locking between them for every decision.
A step() method, called once per tick from outsideOur pick
In a real building, a timer would call step() once a second. Tests call it in a loop and check exact tick numbers. All the moving happens in one method under one lock, so cars never race each other. The cost is that the code models time in whole ticks, which is fine for deciding where cars go.
Which floor next: the sweep
The interesting part of a car is the order it visits its stops. The car keeps going while it has work ahead, and turns only when it has none:
// Keep going while there is work ahead; turn round only when there is none. private Optional<Direction> nextDirection() { if (hasStopsBeyond(heading)) { return Optional.of(heading); } if (hasStopsBeyond(heading.opposite())) { return Optional.of(heading.opposite()); } return Optional.empty(); } private boolean shouldStopHere() { if (carCalls.contains(floor) || callsGoing(heading).contains(floor)) { return true; } // Someone going the other way is picked up only where the car turns round. return callsGoing(heading.opposite()).contains(floor) && !hasStopsBeyond(heading); } private Stop openDoors(long tick) { carCalls.remove(floor); boolean turning = !callsGoing(heading).contains(floor) && !hasStopsBeyond(heading); if (turning && callsGoing(heading.opposite()).contains(floor)) { heading = heading.opposite(); } List<HallCall> served = new ArrayList<>(); if (callsGoing(heading).remove(floor)) { served.add(new HallCall(floor, heading)); } state = CarState.DOORS_OPEN; doorTicksLeft = doorTicks; return new Stop(tick, id, floor, served); }Three methods do the work:
nextDirection()keeps the currentheadingif there is any stop beyond the car in that direction. Otherwise it turns round, and if there are no stops at all, the car goes idle.shouldStopHere()stops for a rider's floor, or for a caller going the car's way. A caller going the other way is picked up only where the car is about to turn, which is when it has no stops beyond.openDoors()clears the rider's floor and answers the hall call at this floor. If the car is turning here, it first flipsheading, so it answers the caller who wants to go the new way.
Here is car A in the demo at the end of this article:
Nearest stop first, or keep going?
Always go to the nearest stop
This sounds efficient. But a busy car between floors 4 and 6 can bounce between them while a rider who pressed 10 waits for ever. Riders who board going up also expect to go up.
Sweep: keep going while there is work ahead, then turnOur pick
Every stop is reached within one sweep up, one sweep down and part of the next, so no rider waits for ever. The car never carries a rider the wrong way. The cost is that a caller just behind a moving car waits for the whole sweep, which is why the next part gives such a call to another car if one is closer.
Which car answers a hall call
When a hall button lights, some car has to come. There is more than one good rule for choosing it, and the building owner will want to change it. This is where the design needs a pattern.
A rule sees each car through CarView, an interface with only getters: the floor, the state, the heading, how many requests are left, and the highest and lowest stops. A rule cannot add a stop or move a car by mistake, because it has no method that does.
The default rule counts how many floors each car must travel before it can stop at the caller's floor, going the caller's way:
public static int floorsToReach(CarView car, HallCall call) { int here = car.floor(); int target = call.floor(); if (car.state() == CarState.IDLE && car.pendingRequests() == 0) { return Math.abs(target - here); } if (car.heading() == Direction.UP) { if (call.direction() == Direction.UP && target >= here) { return target - here; } int top = Math.max(Math.max(here, car.highestStop().orElse(here)), target); if (call.direction() == Direction.DOWN) { return (top - here) + (top - target); } int bottom = Math.min(car.lowestStop().orElse(here), target); return (top - here) + (top - bottom) + (target - bottom); } if (call.direction() == Direction.DOWN && target <= here) { return here - target; } int bottom = Math.min(Math.min(here, car.lowestStop().orElse(here)), target); if (call.direction() == Direction.UP) { return (here - bottom) + (target - bottom); } int top = Math.max(car.highestStop().orElse(here), target); return (here - bottom) + (top - bottom) + (top - target); }An idle car with nothing to do just travels the distance. A car already going up, with the call ahead of it going up, travels the gap. A car going up that is asked for a down call must first reach the top of its run, then come back. A car going up that is asked for an up call below it must go up, down past the caller, and up again. The second half of the method is the same four cases for a car going down.
The other rule ignores distance and spreads the work: LeastBusyStrategy picks the car with the fewest requests left, and the nearer one on a tie.
Neither rule is right in general. One detail shows why. NearestCarStrategy counts floors, not stops, so it ignores that car A must stop at 5 first. With doors open for 2 ticks, A reaches the caller after 5 ticks, while idle B would take 4. A better estimate would add the door time of every stop before the caller. CarView would then expose the car's stops and its door time, ElevatorCar would implement them, and NearestCarStrategy would count the stops. The controller would not change.
Is an interface worth it here?
Put the nearest-car loop inside the controller
This means fewer files. But the controller also holds the lock, the waiting queue and the breakdown handling. Every change to the rule would mean editing and re-testing all of that.
DispatchStrategy, with two implementationsOur pick
A new rule is a new class, and the controller does not change. We wrote two rules, and the figure shows them disagreeing, so the interface is used, not added "just in case". Tests can also pass a rule that throws, to check that the controller survives it.
Pressing a hall button
Now the press itself. Here is requestPickup:
/** Someone on a floor pressed up or down. Returns the car that will come. */ public synchronized Assignment requestPickup(int floor, Direction direction) { refuseCallsFromTheRule(); HallCall call = new HallCall(floor, direction); if (!floors.hasButton(call)) { throw new IllegalArgumentException("Floor " + floor + " has no " + direction + " button"); } Optional<String> current = carServing(call); if (current.isPresent() || waiting.contains(call)) { return Assignment.of(call, current, false); } Optional<String> boarding = carBoardingAt(call); if (boarding.isPresent()) { return Assignment.of(call, boarding, false); } waiting.add(call); assignWaiting(); return Assignment.of(call, carServing(call), true); }The method checks that the button exists. Then it asks whether the call is already lit, which means some car has it, or it is waiting in the queue. A lit button returns the same answer again, with newCall set to false, even if another car has since stopped at that floor. Otherwise, if a car is standing at that floor with its doors open and will leave the caller's way, the caller can walk straight in: the press names that car and lights nothing. A car stopped there going up, whose riders want lower floors, does not count, because it will leave going down. Any other call goes into the waiting queue, and assignWaiting() gives it to a car. The answer is an Assignment: the call, the car that will come, and whether this press lit the button. Its car() is an empty Optional while no car has taken the call.
When is a hall call given to a car?
Decide only when a car comes near
The controller would keep a list of lit buttons, and each car would take whichever one it reaches first. This adapts to how the cars move. But nothing can tell the caller which car is coming, and two cars can head for the same caller and both arrive.
At the press, to exactly one carOur pick
Every lit button belongs to one car, or waits in the queue until a car can take it, so the display on the floor can show "car A" at once, and no two cars ever answer one call. The cost is that the choice can turn out wrong as other calls arrive. A controller could re-check its assignments from time to time. We keep the first choice, and change it only when a car breaks down.
A car breaks down
A car can stop working at any moment, with riders inside and callers waiting for it. Here is what the controller does:
/** The car stops where it is. Its hall calls go to other cars; its riders get out here. */ public synchronized List<HallCall> takeOutOfService(String carId) { refuseCallsFromTheRule(); ElevatorCar car = car(carId); if (car.state() == CarState.OUT_OF_SERVICE) { return List.of(); } List<HallCall> orphaned = car.takeOutOfService(); waiting.addAll(orphaned); assignWaiting(); return orphaned; }The car hands back its hall calls and clears its riders' floors. The controller puts the hall calls in the waiting queue and calls assignWaiting(), the same method a new press uses:
// Gives each waiting call to a car. A call leaves the queue only once a car has it, // and a call no car can take does not hold up the calls behind it. private void assignWaiting() { List<CarView> inService = new ArrayList<>(); for (ElevatorCar car : cars.values()) { if (car.state() != CarState.OUT_OF_SERVICE) { inService.add(car); } } if (inService.isEmpty()) { return; } for (HallCall call : List.copyOf(waiting)) { ElevatorCar chosen = choose(call, inService); if (chosen != null) { chosen.addHallCall(call); waiting.remove(call); } } } // Asks the rule for a car. A rule that throws, or picks a car that is not in // service, is logged and the call keeps waiting. private ElevatorCar choose(HallCall call, List<CarView> inService) { dispatching = true; try { CarView picked = dispatch.choose(call, List.copyOf(inService)); if (picked == null) { warn("The dispatch rule picked no car for " + call, null); return null; } for (CarView candidate : inService) { if (candidate == picked) { return (ElevatorCar) candidate; } } warn("The dispatch rule picked a car that is not in service for " + call, null); } catch (RuntimeException e) { warn("Could not dispatch " + call, e); } finally { dispatching = false; } return null; }assignWaiting walks a copy of the queue. For each call, it asks the rule for a car, gives the call to that car, and only then removes the call from the queue. If the rule throws, or picks a car that is not in service, choose logs it and returns null, and that call stays in the queue. The loop then moves on, so one call the rule cannot place does not hold up the calls behind it. If no car is in service, the loop does not run at all. step() calls assignWaiting() at the start of every tick, so a waiting call is tried again until some car takes it.
The rule runs while the controller holds its lock, and it is code the controller does not control. If it pressed a button or took a car out of service from inside choose(), it would change the queue and the cars in the middle of the loop. So choose sets a dispatching flag while the rule runs, and every method that changes something refuses to run while it is set:
// The safety net must not stop the cars: a log that fails is dropped. private void warn(String message, Throwable cause) { try { log.log(System.Logger.Level.WARNING, message, cause); } catch (RuntimeException ignored) { // Nothing else can report a failing log. } } private void refuseCallsFromTheRule() { if (dispatching) { throw new IllegalStateException("The dispatch rule must not call back into the controller"); } }A rule that calls back in gets an IllegalStateException, which choose catches and logs like any other failure. The logger comes in through the constructor, and warn drops a log call that throws, because a failing log must not stop the cars either.
What should happen when the dispatch rule fails?
Throw the exception from requestPickup
The bug is loud and easy to find. But the button has already been pressed, and the person on that floor is still waiting. If the press throws, the call is lost and no car ever comes. When the same failure happens inside step(), every car in the building stops moving.
Log it, keep the call waiting, and try again next tickOur pick
An exception from the rule never loses a call and never stops the cars. Car calls and calls already assigned keep being served. An Error, such as running out of memory, is not caught, because nothing sensible can carry on after one. The call shows as lit with no car named, and the log says why. The cost is that a bug in a rule shows up as a warning, not a crash, so someone has to watch the logs.
Many buttons, one controller
Every floor and every car panel can press at the same moment, while the timer calls step(). None of them talks to a car, and no car talks to another car. Everything goes through the controller.
Having one object in the middle also makes the threading simple. The design keeps it safe with one lock: every public method of ElevatorController is synchronized.
Look at what a press does to shared state. It reads every car to see whether the call is lit, adds to the queue, reads every car again in the rule, and adds a floor to one car's TreeSet. A TreeSet is not safe for two threads at once. If two presses add floors to the same car together, the tree can lose one of them, or break so that later reads fail.
The project includes a check, demo/RaceCheck.java. It builds four cars over 20 floors. Sixteen threads press random hall buttons 2,000 times each, while another thread calls step() in a loop. Then the cars run for 10,000 more ticks, far more than they need to answer every call left, and the check counts each call lit and each call answered:
32000 presses from 16 threads buttons lit 785, hall calls answered 785 calls never answered 0, calls answered twice 0
Every button that lit was answered, exactly once. The two counts change from run to run, because the presses interleave differently, but with the lock they match. We also ran the same check with synchronized removed from requestPickup, six times. Within moments most pressing threads died, and so did the thread calling step(). Some died with a NullPointerException from inside a car's TreeSet, and some with an exception from the waiting queue. Most died with the controller's own IllegalStateException, because a press saw the dispatching flag that another thread's step() had set. That flag only means something under the lock. In two runs the program itself crashed before printing any counts. Every run that finished left lit buttons that no car would ever answer, and two of them answered a call twice. A call is answered twice when two presses of the same button both see it unlit, both add it to the waiting queue, and two cars each take a copy. None of this shows up when testing one press at a time.
Where does the lock go?
A lock per car
Presses for different cars would never wait for each other. But the rule reads every car to choose one, and a breakdown moves calls from one car to others. Both need several cars locked at once, in a fixed order, or two threads can each hold one lock and wait for the other for ever.
One lock on the controllerOur pick
The rule sees all the cars at one moment, and a breakdown moves calls in one step. Each method does a little work on a few cars and calls no outside code except the rule and the logger. People press buttons a few times a second at most, so a press waiting a moment for the lock goes unnoticed.
The final design
ElevatorController is the core. It owns the cars, the waiting queue and the one lock, and it reaches the rule for picking a car only through DispatchStrategy, which sees the cars only through the read-only CarView.
| S.No. | The question | What we chose | Why |
|---|---|---|---|
| 1 | Should a floor be a class? | A floor is an int, and FloorRange says which floors exist | A floor has no behaviour, and the one rule about floors fits in one record |
| 2 | One Request type, or hall calls and car calls apart? | HallCall is a record; a car call is a floor in the car's own set | Each piece of data lives with the only code that uses it |
| 3 | Real time, or ticks? | A step() method, called once per tick from outside | Tests check exact tick numbers, and cars never race each other |
| 4 | Nearest stop first, or keep going? | Sweep: keep going while there is work ahead, then turn | No rider waits for ever or rides the wrong way |
| 5 | Is an interface worth it here? | DispatchStrategy, with two implementations | A new rule is a new class, and the controller does not change |
| 6 | When is a hall call given to a car? | At the press, to exactly one car | The display can name the car at once, and no two cars answer one call |
| 7 | What should happen when the dispatch rule fails? | Log it, keep the call waiting, and try again next tick | A failing rule never loses a call and never stops the cars |
| 8 | Where does the lock go? | One lock on the controller | The rule sees every car at one moment, and a breakdown moves calls in one step |
Here is one press of 7 DOWN, end to end:
- A caller on floor 7 presses DOWN, and the floor panel calls
requestPickup(7, DOWN). The method issynchronized, so the press takes the controller's lock here and holds it until it returns. FloorRange.hasButtonchecks that the button exists.carServingandcarBoardingAtcheck that no car has the call and no car is ready to leave floor 7 going down. The call goes intowaiting.assignWaitingcollects the cars in service, andchoosesetsdispatchingand callsDispatchStrategy.choose. This is the outside call: the rule is code the controller does not control, and it runs under the lock. If it throws, the call stays inwaitingfor the next tick.addHallCallputs floor 7 in the chosen car'sdownCalls, and only then does the call leavewaiting.requestPickupreturns anAssignmentnaming the car, so the display can show it, and the lock is released.- On each later tick, the controller's
step()takes the same lock and calls the car'sstep(tick), which moves the car one floor or holds it at a stop. When the car stops at floor 7 going down,openDoorsanswers 7 DOWN and returns aStop.
The complete code
Here is the whole project. Click any class name to jump to its file, or use Find a file to search. Badges in the tree show what each file is: a class, an interface, an enum or a record.
package elevator; import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Deque;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.Optional; import dispatch.DispatchStrategy;import request.Assignment;import request.Direction;import request.HallCall;import status.CarStatus;import status.Stop; /** * The building's controller: takes button presses, gives each hall call to * one car, and moves every car one tick at a time. Every public method holds * this object's lock, so presses from many floors and the tick never overlap. */public class ElevatorController { private final FloorRange floors; private final DispatchStrategy dispatch; private final System.Logger log; private final Map<String, ElevatorCar> cars = new LinkedHashMap<>(); // Lit hall buttons that no car has taken yet, oldest first. private final Deque<HallCall> waiting = new ArrayDeque<>(); private long tick; // True while the dispatch rule runs, so a rule cannot call back in and change what it is reading. private boolean dispatching; public ElevatorController(List<String> carIds, FloorRange floors, int doorTicks, DispatchStrategy dispatch, System.Logger log) { this.floors = Objects.requireNonNull(floors, "floors"); this.dispatch = Objects.requireNonNull(dispatch, "dispatch"); this.log = Objects.requireNonNull(log, "log"); if (carIds.isEmpty()) { throw new IllegalArgumentException("A building needs at least one car"); } if (doorTicks < 1) { throw new IllegalArgumentException("Doors must stay open for at least one tick"); } for (String id : carIds) { Objects.requireNonNull(id, "car id"); if (cars.putIfAbsent(id, new ElevatorCar(id, floors.lowest(), doorTicks)) != null) { throw new IllegalArgumentException("Two cars are called " + id); } } } /** Someone on a floor pressed up or down. Returns the car that will come. */ public synchronized Assignment requestPickup(int floor, Direction direction) { refuseCallsFromTheRule(); HallCall call = new HallCall(floor, direction); if (!floors.hasButton(call)) { throw new IllegalArgumentException("Floor " + floor + " has no " + direction + " button"); } Optional<String> current = carServing(call); if (current.isPresent() || waiting.contains(call)) { return Assignment.of(call, current, false); } Optional<String> boarding = carBoardingAt(call); if (boarding.isPresent()) { return Assignment.of(call, boarding, false); } waiting.add(call); assignWaiting(); return Assignment.of(call, carServing(call), true); } /** A rider inside a car pressed a floor. Returns false if nothing changes. */ public synchronized boolean pressCarButton(String carId, int floor) { refuseCallsFromTheRule(); ElevatorCar car = car(carId); if (!floors.contains(floor)) { throw new IllegalArgumentException("There is no floor " + floor); } return car.addCarCall(floor); } /** Moves time on by one tick: every car stops, waits or moves one floor. */ public synchronized List<Stop> step() { refuseCallsFromTheRule(); tick++; assignWaiting(); List<Stop> stops = new ArrayList<>(); for (ElevatorCar car : cars.values()) { car.step(tick).ifPresent(stops::add); } return stops; } /** The car stops where it is. Its hall calls go to other cars; its riders get out here. */ public synchronized List<HallCall> takeOutOfService(String carId) { refuseCallsFromTheRule(); ElevatorCar car = car(carId); if (car.state() == CarState.OUT_OF_SERVICE) { return List.of(); } List<HallCall> orphaned = car.takeOutOfService(); waiting.addAll(orphaned); assignWaiting(); return orphaned; } public synchronized void returnToService(String carId) { refuseCallsFromTheRule(); car(carId).returnToService(); assignWaiting(); } public synchronized List<CarStatus> status() { List<CarStatus> all = new ArrayList<>(); for (ElevatorCar car : cars.values()) { all.add(car.status()); } return all; } public synchronized List<HallCall> waitingCalls() { return List.copyOf(waiting); } public synchronized long tick() { return tick; } // Gives each waiting call to a car. A call leaves the queue only once a car has it, // and a call no car can take does not hold up the calls behind it. private void assignWaiting() { List<CarView> inService = new ArrayList<>(); for (ElevatorCar car : cars.values()) { if (car.state() != CarState.OUT_OF_SERVICE) { inService.add(car); } } if (inService.isEmpty()) { return; } for (HallCall call : List.copyOf(waiting)) { ElevatorCar chosen = choose(call, inService); if (chosen != null) { chosen.addHallCall(call); waiting.remove(call); } } } // Asks the rule for a car. A rule that throws, or picks a car that is not in // service, is logged and the call keeps waiting. private ElevatorCar choose(HallCall call, List<CarView> inService) { dispatching = true; try { CarView picked = dispatch.choose(call, List.copyOf(inService)); if (picked == null) { warn("The dispatch rule picked no car for " + call, null); return null; } for (CarView candidate : inService) { if (candidate == picked) { return (ElevatorCar) candidate; } } warn("The dispatch rule picked a car that is not in service for " + call, null); } catch (RuntimeException e) { warn("Could not dispatch " + call, e); } finally { dispatching = false; } return null; } // The safety net must not stop the cars: a log that fails is dropped. private void warn(String message, Throwable cause) { try { log.log(System.Logger.Level.WARNING, message, cause); } catch (RuntimeException ignored) { // Nothing else can report a failing log. } } private void refuseCallsFromTheRule() { if (dispatching) { throw new IllegalStateException("The dispatch rule must not call back into the controller"); } } // A car standing at this floor with its doors open, about to go the caller's way. private Optional<String> carBoardingAt(HallCall call) { for (ElevatorCar car : cars.values()) { if (car.isBoarding(call)) { return Optional.of(car.id()); } } return Optional.empty(); } private Optional<String> carServing(HallCall call) { for (ElevatorCar car : cars.values()) { if (car.hasHallCall(call)) { return Optional.of(car.id()); } } return Optional.empty(); } private ElevatorCar car(String carId) { ElevatorCar car = cars.get(carId); if (car == null) { throw new IllegalArgumentException("There is no car " + carId); } return car; }}demo/Main.java runs a building with floors 0 to 10 and three cars through a morning. Riders press floors, callers press hall buttons, car B breaks down, and then every car is switched off for a while:
Floors 0 to 10. Cars A, B and C wait at floor 0. Doors stay open for 2 ticks. t=0 in car C, riders press 9, 3, 6 t=0 press 7 DOWN -> car A t=3 car C stops at 3 t=4 press 5 UP -> car A t=4 press 2 UP -> car B t=4 press 7 DOWN -> car A (already lit) t=5 car A stops at 5, picks up 5 UP t=6 car B stops at 2, picks up 2 UP t=6 in car A, riders press 9 t=8 car C stops at 6 t=8 in car B, riders press 5 t=8 press 6 DOWN -> car B t=10 car A: floor 8, MOVING_UP, stops [7, 9] t=10 car B: floor 4, MOVING_UP, stops [5, 6] t=10 car C: floor 6, DOORS_OPEN, stops [9] t=10 car B breaks down at floor 4. Its hall calls [6 DOWN] go to other cars. t=10 a rider still in car B presses 3: nothing happens, the car is out of service t=10 car A: floor 8, MOVING_UP, stops [6, 7, 9] t=10 car B: floor 4, OUT_OF_SERVICE, stops [] t=10 car C: floor 6, DOORS_OPEN, stops [9] t=11 car A stops at 9 t=13 car C stops at 9 t=15 car A stops at 7, picks up 7 DOWN t=18 car A stops at 6, picks up 6 DOWN t=30 car A: floor 6, IDLE, stops [] t=30 car B: floor 4, OUT_OF_SERVICE, stops [] t=30 car C: floor 9, IDLE, stops [] t=30 cars A and C are switched off too t=30 press 3 UP -> no car yet, it waits t=32 car C is back in service and takes [3] from the waiting calls t=38 car C stops at 3, picks up 3 UP t=38 press 10 UP -> rejected: Floor 10 has no UP button
Notice four things in the output. The riders in car C pressed 9, 3 and 6, and C stopped at 3, 6 and 9, in floor order. At tick 10 car A is at floor 8 with 7 still in its stops: it passed the caller going down and comes back for them at tick 15. When car B broke down, its hall call 6 DOWN went to car A, while its rider's floor 5 disappeared, and a press on its dead panel did nothing. And with every car switched off, 3 UP waited, and car C took it as soon as it came back.
Follow-up questions
After the core design, the interviewer adds a requirement to see how the design bends. For each one, say which class changes and which do not.
| The interviewer asks | What changes | What does not |
|---|---|---|
| "Cars have a weight limit." | A full car must not leave its callers stranded, so the controller hands a full car's hall calls back to the waiting queue, the path a breakdown uses. CarView gains isFull() so the rule skips full cars. A full car still stops for its riders. | The sweep, the records, the lock. |
| "Count door time in the estimate." | CarView gains the car's stops and its door time, ElevatorCar implements them, and NearestCarStrategy adds the door time of each stop before the caller. | The controller, the sweep. |
| "Add a fire service mode." | A mode on the car that drops every call and sends it to the ground floor. This is where the State pattern earns its place, as a class per mode. | Dispatch rules, records. |
| "Riders choose their floor in the lobby, before boarding." | A new kind of hall call with a destination, and a rule that groups riders going to nearby floors into one car. requestPickup takes the destination. | The car's sweep. |
| "Morning rush: send idle cars back to the lobby." | A small parking rule run each tick that gives idle cars a stop at floor 0. | Everything else. |
| "Some cars serve only floors 10 to 20." | Each car gets its own FloorRange, and the controller passes the rule only the cars that serve the call's floor. | The rule itself, the car's sweep. |
| "Re-plan assignments as cars move." | assignWaiting gains a pass that takes calls back and dispatches them again when a much closer car appears. | Cars, records, the sweep. |
| "Show every car's position on every floor." | An ElevatorListener interface. The timer hands it each tick's stops and positions, outside the controller's lock. This is the Observer pattern. | Cars, rules, the sweep. |
| "Several buildings." | One controller per building. | Nothing inside a building. |
In most rows the change lands in a rule, a car's own logic, or a new small piece beside the controller.
What the interviewer looks for
Mid-level
A mid-level candidate shows a car with a floor, a direction and a list of stops, a controller that holds the cars, and enums instead of strings for direction and state. They explain how a car moves through its stops and get the up and down buttons right at the ends of the building. They mention that presses from many floors need some locking.
Senior
A senior candidate shows everything above and gives the reasons. They explain the sweep and why it never leaves a rider waiting for ever. They put the choice of car behind an interface and show two rules that disagree. They give each hall call to exactly one car and say what happens when that car breaks down. They drive the cars with ticks, so time can be tested, and they say where the lock goes and why one is enough.
Staff+
A staff candidate leads the conversation through the trade-offs without being asked. They point out what the estimate ignores, such as door time and calls that arrive later, and when an early assignment turns out wrong. They say how a broken rule is kept from losing calls or stopping the cars. They know what changes for destination dispatch in a tall building, where riders choose floors in the lobby and the rule groups them.
Common mistakes
- A class for every noun.
Floor,DoorandButtonclasses with nothing inside them add files and layers. A floor is a number and a door is a state. - Serving the nearest stop first. A busy car can then leave a rider waiting for ever. Sweep in one direction, then turn.
- Picking up a caller going the wrong way. A rider who wants to go down should not board a car on its way up. Answer them where the car turns.
- No owner for a hall call. If any car may answer any lit button, two cars can arrive for one caller, and a breakdown has nothing to hand back.
- Losing calls when something fails. Remove a call from the queue only after a car has it, and keep it waiting if the rule throws or no car is in service.
- A thread per car that sleeps. It makes every test slow and timing-dependent. Move time with
step(). - Locks sprinkled on the cars. The rule reads all the cars at once. One lock on the controller is simpler and correct.
Summary
- Ask first. When the car is picked, how time is modelled and whether cars can break down all change the code.
- Keep only the nouns with a job. A floor is a number, a door is a state, and a passenger is outside the code.
- Each car sweeps: it keeps going while it has work ahead, and turns only when it has none.
- Put the choice of car behind
DispatchStrategy, and let rules see cars only through a read-onlyCarView. - Give every hall call to exactly one car at the press, and hand its calls to other cars when it breaks down.
- Take a call off the queue only after a car has it, so a broken rule or an empty building never loses one.
- Drive the cars with ticks and one lock, so time can be tested and presses from every floor stay safe.