The elevator problem has two parts that interviewers probe separately: the state machine for one car (what it may do next) and the scheduling across cars (which car answers a call). Keeping them separate is most of the design.
Requirements to confirm
- N cars, M floors. Hall calls (someone on floor 6 presses "down") and car calls (someone inside presses 2).
- Doors must be closed while moving. A car can be taken out of service.
- Out of scope unless asked: weight limits, express zones, emergency modes.
The state machine
| From | Allowed next states |
|---|---|
| IDLE | MOVING_UP, MOVING_DOWN, DOORS_OPEN, OUT_OF_SERVICE |
| MOVING_UP | DOORS_OPEN (arrived at a stop), OUT_OF_SERVICE |
| MOVING_DOWN | DOORS_OPEN, OUT_OF_SERVICE |
| DOORS_OPEN | DOORS_CLOSING |
| DOORS_CLOSING | DOORS_OPEN (something in the way), IDLE, MOVING_UP, MOVING_DOWN |
| OUT_OF_SERVICE | IDLE |
The illegal transitions are the interesting part: moving with the doors open (DOORS_OPEN → MOVING_*), reversing direction without stopping (MOVING_UP → MOVING_DOWN), and moving straight out of maintenance. Encode the table once and enforce it in one place:
enum State {
IDLE, MOVING_UP, MOVING_DOWN, DOORS_OPEN, DOORS_CLOSING, OUT_OF_SERVICE;
private static final Map<State, Set<State>> NEXT = new EnumMap<>(State.class);
static {
NEXT.put(IDLE, EnumSet.of(MOVING_UP, MOVING_DOWN, DOORS_OPEN, OUT_OF_SERVICE));
NEXT.put(MOVING_UP, EnumSet.of(DOORS_OPEN, OUT_OF_SERVICE));
NEXT.put(MOVING_DOWN, EnumSet.of(DOORS_OPEN, OUT_OF_SERVICE));
NEXT.put(DOORS_OPEN, EnumSet.of(DOORS_CLOSING));
NEXT.put(DOORS_CLOSING, EnumSet.of(DOORS_OPEN, IDLE, MOVING_UP, MOVING_DOWN));
NEXT.put(OUT_OF_SERVICE, EnumSet.of(IDLE));
}
boolean canGoTo(State next) { return NEXT.get(this).contains(next); }
}
One car: the LOOK algorithm
First-come-first-served makes a car zigzag. The classic fix comes from disk scheduling. SCAN keeps moving in one direction to the end of the shaft, serving stops on the way, then reverses. LOOK reverses as soon as there are no more stops ahead, which is what real elevators do. Two sorted sets of stops, above and below the car, make "next stop in this direction" an O(log n) lookup:
final class Elevator {
private int floor;
private State state = State.IDLE;
private final TreeSet<Integer> stopsAbove = new TreeSet<>();
private final TreeSet<Integer> stopsBelow = new TreeSet<>();
synchronized void addStop(int target) {
if (target > floor) stopsAbove.add(target);
else if (target < floor) stopsBelow.add(target);
// target == floor: open the doors (omitted)
}
/** LOOK: keep going while there are stops ahead in this direction, then reverse. */
synchronized OptionalInt nextStop() {
boolean down = state == State.MOVING_DOWN;
Integer next = down ? stopsBelow.floor(floor) : stopsAbove.ceiling(floor);
if (next == null) next = down ? stopsAbove.ceiling(floor) : stopsBelow.floor(floor);
return next == null ? OptionalInt.empty() : OptionalInt.of(next);
}
synchronized void transition(State to) {
if (!state.canGoTo(to)) throw new IllegalStateException(state + " -> " + to + " is not allowed");
state = to;
}
}
Many cars: a swappable dispatch strategy
Which car should answer a hall call? A good default: the nearest car that is idle or already heading towards the caller in the same direction, with a penalty for cars that would have to turn around. Real buildings change policy by time of day, sending idle cars to the lobby in the morning rush, so dispatch is a strategy:
enum Direction { UP, DOWN }
record HallCall(int floor, Direction direction) {}
// Elevator also exposes floor(), isIdle(), inService() and isHeadingTowards(call); omitted above.
interface DispatchStrategy { Elevator choose(HallCall call, List<Elevator> cars); }
final class NearestCompatible implements DispatchStrategy {
private static final int TURNAROUND_PENALTY = 100;
public Elevator choose(HallCall call, List<Elevator> cars) {
return cars.stream()
.filter(Elevator::inService)
.min(Comparator.comparingInt(car -> cost(car, call)))
.orElseThrow(() -> new IllegalStateException("no elevator in service"));
}
// Idle cars, or cars already heading to the caller in the caller's direction, are cheapest.
private int cost(Elevator car, HallCall call) {
int distance = Math.abs(car.floor() - call.floor());
return car.isIdle() || car.isHeadingTowards(call) ? distance : distance + TURNAROUND_PENALTY;
}
}
// Swap the policy without touching the cars:
// building.setDispatch(isMorningPeak ? new LobbyFirst() : new NearestCompatible());
Concurrency
Buttons are pressed from many places at once. The simplest safe structure: each car is driven by its own single-threaded controller, an event loop that takes stops from a thread-safe queue, so a car's state is only ever changed by one thread. The dispatcher only adds stops to cars. With synchronized methods on the car, as above, the state machine stays consistent either way.
Interview checklist
- Separate per-car state from dispatch across cars.
- Write the transition table, and name the illegal transitions.
- Enforce transitions in one method that throws.
- Explain SCAN vs LOOK, implemented with sorted sets.
- Make dispatch a strategy, and say how you'd swap it.
Exercise
Write the State enum and a test that every illegal transition throws. Then simulate one car with stops at floors 5, 2 and 8 starting from floor 3 going up, and check that LOOK visits 5, 8, then 2.
Do it by hand
Interactive drills for the parts the simulator can't show. Scored, with your best result saved in your browser.
Further reading
- Eric Freeman and Elisabeth Robson, Head First Design Patterns (O'Reilly). The friendliest introduction to the classic patterns.
- Refactoring.Guru: design patterns, with diagrams and Java examples for each pattern.
- Joshua Bloch, Effective Java. Idiomatic Java, including builders, immutability and concurrency.