Load/Bearing
Low-level design · 22 of 22

Elevator system: state machine and scheduling

Model each car as a state machine that refuses illegal moves, and keep the dispatch policy swappable.

3 min read

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

The state machine

FromAllowed next states
IDLEMOVING_UP, MOVING_DOWN, DOORS_OPEN, OUT_OF_SERVICE
MOVING_UPDOORS_OPEN (arrived at a stop), OUT_OF_SERVICE
MOVING_DOWNDOORS_OPEN, OUT_OF_SERVICE
DOORS_OPENDOORS_CLOSING
DOORS_CLOSINGDOORS_OPEN (something in the way), IDLE, MOVING_UP, MOVING_DOWN
OUT_OF_SERVICEIDLE

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

Practise 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.

Workshop drill

Do it by hand

Interactive drills for the parts the simulator can't show. Scored, with your best result saved in your browser.

Elevator: LOOK order Elevator: legal moves

Further reading