Skip to lesson

LLD: elevator system

Ten floors, three lifts and people pressing buttons at the same moment: which lift answers, and in what order does each one stop? The round tests states, strategies and tracing a simulation step by step.

Requirements: cars, floor requests and cabin requests

A hall request is a call from a floor: someone on floor 6 pressed the button, and the controller must choose a car.

Two kinds of request drive the whole design. This is the scope to agree on.

Text
Building:  floors 0-10, 2 cars (A and B)Hall:      request(floor) from a floor; controller picks a carCabin:     press(car, floor) inside a car; goes to that car onlyCar:       one floor per tick, stops in its current direction firstStates:    IDLE, MOVING_UP, MOVING_DOWN, MAINTENANCEDispatch:  nearest car by default; strategy can changeOut:       doors timing, weight, fire mode, scheduling by time of day

A cabin request comes from inside a car ("take me to floor 9") and always goes to that car.

Settle the scope early: how many floors and cars, whether the hall button has a direction, and whether you must model doors, weight and emergencies. In 45 minutes, a good answer covers requests, car states, a dispatcher and a simulation; doors and weight are follow-ups.

Elevator states: idle, moving up, moving down, maintenance

An elevator state is what the car is doing right now (idle, moving up, moving down or in maintenance), and it decides what the car does next.

One car walks through its states: it finishes the stops in its direction, then turns around.

Example 1 · One car: states and direction

ElevatorStateDemo.javaJava
import java.util.TreeSet;
enum ElevatorState { IDLE, MOVING_UP, MOVING_DOWN, MAINTENANCE }
class Elevator {    final String id;    int floor;    ElevatorState state = ElevatorState.IDLE;    final TreeSet<Integer> stops = new TreeSet<>();
    Elevator(String id, int floor) { this.id = id; this.floor = floor; }
    void addStop(int f) {        if (state != ElevatorState.MAINTENANCE) stops.add(f);    }
    // one tick: open the doors here, or move one floor    String step() {        if (state == ElevatorState.MAINTENANCE) return id + " under maintenance";        if (stops.remove(floor)) {            if (stops.isEmpty()) state = ElevatorState.IDLE;            return id + " opens doors at " + floor;        }        if (stops.isEmpty()) {            state = ElevatorState.IDLE;            return id + " idle at " + floor;        }        if (state == ElevatorState.MOVING_UP && stops.higher(floor) == null) state = ElevatorState.MOVING_DOWN;        else if (state == ElevatorState.MOVING_DOWN && stops.lower(floor) == null) state = ElevatorState.MOVING_UP;        else if (state == ElevatorState.IDLE) state = stops.ceiling(floor) != null ? ElevatorState.MOVING_UP : ElevatorState.MOVING_DOWN;        floor += state == ElevatorState.MOVING_UP ? 1 : -1;        return id + " " + state + " to " + floor;    }}
public class ElevatorStateDemo {    public static void main(String[] args) {        Elevator a = new Elevator("A", 3);        a.addStop(5);        a.addStop(1);        for (int tick = 1; tick <= 8; tick++) {            System.out.println("t" + tick + ": " + a.step() + "  stops " + a.stops);        }        a.state = ElevatorState.MAINTENANCE;        a.addStop(7);        System.out.println("t9: " + a.step() + "  stops " + a.stops);    }}
Output
t1: A MOVING_UP to 4  stops [1, 5]
t2: A MOVING_UP to 5  stops [1, 5]
t3: A opens doors at 5  stops [1]
t4: A MOVING_DOWN to 4  stops [1]
t5: A MOVING_DOWN to 3  stops [1]
t6: A MOVING_DOWN to 2  stops [1]
t7: A MOVING_DOWN to 1  stops [1]
t8: A opens doors at 1  stops []
t9: A under maintenance  stops []

What this code does

  • From floor 3 with stops 5 and 1, the idle car finds a stop above (ceiling(3) is 5) and goes up first, then turns down for floor 1 without going back up.
  • Opening the doors takes a whole tick and removes that stop from the set.
  • In MAINTENANCE, addStop ignores new stops and step does nothing, so the car is safe to repair.

An IDLE car waits, a MOVING_UP car keeps going up while stops remain above it, a MOVING_DOWN car does the same downwards, and a MAINTENANCE car ignores every request. Finishing the stops in your direction before turning is how real lifts work, and it stops a car from bouncing between floors 2 and 9.

Keep the pending stops in a TreeSet<Integer>: higher(floor) tells you whether any stop is still above, and lower(floor) whether any is below.

Predict the output

Predict higher and lower

A car keeps its pending stops in a TreeSet. What do the two calls print?

Round 1 of 2

TreeSet<Integer> stops = new TreeSet<>(List.of(2, 7));
int floor = 4;
System.out.println(stops.higher(floor) + " " + stops.lower(floor));

Dispatcher strategy: nearest car or least busy

A dispatcher is the strategy that chooses a car for a hall request. The controller passes the request floor and the cars, and gets a car back.

Two dispatch rules behind one interface, tried on the same cars.

Example 2 · Nearest car versus least busy

DispatchDemo.javaJava
import java.util.Comparator;import java.util.List;import java.util.Optional;
record Car(String id, int floor, int pendingStops, boolean inMaintenance) { }
interface DispatchStrategy {    Optional<Car> choose(List<Car> cars, int requestFloor);}
class NearestCar implements DispatchStrategy {    public Optional<Car> choose(List<Car> cars, int requestFloor) {        return cars.stream()                .filter(c -> !c.inMaintenance())                .min(Comparator.comparingInt(c -> Math.abs(c.floor() - requestFloor)));    }}
class LeastBusy implements DispatchStrategy {    public Optional<Car> choose(List<Car> cars, int requestFloor) {        return cars.stream()                .filter(c -> !c.inMaintenance())                .min(Comparator.comparingInt(Car::pendingStops)                        .thenComparingInt(c -> Math.abs(c.floor() - requestFloor)));    }}
public class DispatchDemo {    public static void main(String[] args) {        List<Car> cars = List.of(                new Car("A", 6, 4, false),                new Car("B", 1, 0, false),                new Car("C", 7, 0, true));
        for (DispatchStrategy strategy : List.of(new NearestCar(), new LeastBusy())) {            String name = strategy.getClass().getSimpleName();            System.out.println(name + " for floor 7: " + strategy.choose(cars, 7).map(Car::id).orElse("none"));        }    }}
Output
NearestCar for floor 7: A
LeastBusy for floor 7: B

What this code does

  • Car C is on floor 7 but in maintenance, so both strategies skip it.
  • NearestCar sends A (1 floor away) even though A already has 4 stops; LeastBusy sends the empty car B from floor 1.
  • Neither rule is always right, which is exactly why the rule is a strategy the building can choose.

Nearest car (smallest distance in floors) gives short waits; least busy (fewest pending stops) spreads the work. Both must skip cars in maintenance.

Ties need a fixed rule, such as the first car in the list, so the same input always gives the same car.

Simulating steps in a loop

A tick is one simulation step: every car either opens its doors at the current floor or moves one floor.

A loop calls step() on each car for a few ticks and prints what happened.

Example 3 · A simulation loop with two cars

SimulationDemo.javaJava
import java.util.List;import java.util.TreeSet;
enum ElevatorState { IDLE, MOVING_UP, MOVING_DOWN, MAINTENANCE }
class Elevator {    final String id;    int floor;    ElevatorState state = ElevatorState.IDLE;    final TreeSet<Integer> stops = new TreeSet<>();
    Elevator(String id, int floor) { this.id = id; this.floor = floor; }
    void addStop(int f) {        if (state != ElevatorState.MAINTENANCE) stops.add(f);    }
    // one tick: open the doors here, or move one floor    String step() {        if (state == ElevatorState.MAINTENANCE) return id + " under maintenance";        if (stops.remove(floor)) {            if (stops.isEmpty()) state = ElevatorState.IDLE;            return id + " opens doors at " + floor;        }        if (stops.isEmpty()) {            state = ElevatorState.IDLE;            return id + " idle at " + floor;        }        if (state == ElevatorState.MOVING_UP && stops.higher(floor) == null) state = ElevatorState.MOVING_DOWN;        else if (state == ElevatorState.MOVING_DOWN && stops.lower(floor) == null) state = ElevatorState.MOVING_UP;        else if (state == ElevatorState.IDLE) state = stops.ceiling(floor) != null ? ElevatorState.MOVING_UP : ElevatorState.MOVING_DOWN;        floor += state == ElevatorState.MOVING_UP ? 1 : -1;        return id + " " + state + " to " + floor;    }}
public class SimulationDemo {    public static void main(String[] args) {        Elevator a = new Elevator("A", 0);        Elevator b = new Elevator("B", 8);        a.addStop(2);        b.addStop(6);        b.addStop(9);        List<Elevator> cars = List.of(a, b);
        for (int tick = 1; tick <= 6; tick++) {            StringBuilder line = new StringBuilder("t" + tick + ":");            for (Elevator car : cars) {                line.append("  ").append(car.step());            }            System.out.println(line);            if (tick == 2) {                a.addStop(1);   // someone inside A presses 1 on the way up                System.out.println("    cabin request: A -> 1");            }        }    }}
Output
t1:  A MOVING_UP to 1  B MOVING_UP to 9
t2:  A MOVING_UP to 2  B opens doors at 9
    cabin request: A -> 1
t3:  A opens doors at 2  B MOVING_DOWN to 8
t4:  A MOVING_DOWN to 1  B MOVING_DOWN to 7
t5:  A opens doors at 1  B MOVING_DOWN to 6
t6:  A idle at 1  B opens doors at 6

What this code does

  • Each tick asks every car for one step(), so the output reads like a timeline. B is idle at 8 with stops 6 and 9; ceiling(8) is 9, so it goes up first.
  • The cabin request for floor 1 arrives while A is going up to 2. A finishes floor 2, then turns down, as the direction rule says.
  • Fixed starting floors and requests make the run repeatable, so you can trace it by hand and compare.

A loop that calls step() once per tick turns a timing problem into plain, repeatable output.

Trace the simulation by hand before you trust it: for each tick, write the car's floor, its state and its pending stops. If your trace and the printed output differ, the bug is in the direction rule.

Trace the code

Trace one car, tick by tick

Step through the loop and watch the stops, the floor and the direction.

import java.util.TreeSet;
public class CarTrace {
public static void main(String[] args) {
TreeSet<Integer> stops = new TreeSet<>();
stops.add(2);
stops.add(5);
int floor = 3;
boolean up = true;
for (int tick = 1; tick <= 7; tick++) {
if (stops.remove(floor)) {
System.out.println("tick " + tick + ": open at " + floor);
} else {
if (up && stops.higher(floor) == null) up = false;
floor += up ? 1 : -1;
System.out.println("tick " + tick + ": at " + floor);
}
}
}
}

Variables

stops
{2, 5}

Output

(nothing printed yet)

Line 7The car has two pending stops, floors 2 and 5.

Step 1 of 27

Single-file design with a demo run

The elevator controller takes hall and cabin requests, asks the dispatcher for a car and runs the ticks.

The whole design in one file: one car goes into maintenance, and a few requests arrive.

Example 4 · The elevator controller in one file

ElevatorControllerDemo.javaJava
import java.util.Comparator;import java.util.List;import java.util.Optional;import java.util.TreeSet;
enum ElevatorState { IDLE, MOVING_UP, MOVING_DOWN, MAINTENANCE }
class Elevator {    final String id;    int floor;    ElevatorState state = ElevatorState.IDLE;    final TreeSet<Integer> stops = new TreeSet<>();
    Elevator(String id, int floor) { this.id = id; this.floor = floor; }
    void addStop(int f) {        if (state != ElevatorState.MAINTENANCE) stops.add(f);    }
    // one tick: open the doors here, or move one floor    String step() {        if (state == ElevatorState.MAINTENANCE) return id + " under maintenance";        if (stops.remove(floor)) {            if (stops.isEmpty()) state = ElevatorState.IDLE;            return id + " opens doors at " + floor;        }        if (stops.isEmpty()) {            state = ElevatorState.IDLE;            return id + " idle at " + floor;        }        if (state == ElevatorState.MOVING_UP && stops.higher(floor) == null) state = ElevatorState.MOVING_DOWN;        else if (state == ElevatorState.MOVING_DOWN && stops.lower(floor) == null) state = ElevatorState.MOVING_UP;        else if (state == ElevatorState.IDLE) state = stops.ceiling(floor) != null ? ElevatorState.MOVING_UP : ElevatorState.MOVING_DOWN;        floor += state == ElevatorState.MOVING_UP ? 1 : -1;        return id + " " + state + " to " + floor;    }}
interface DispatchStrategy {    Optional<Elevator> choose(List<Elevator> cars, int floor);}
class NearestCar implements DispatchStrategy {    public Optional<Elevator> choose(List<Elevator> cars, int floor) {        return cars.stream()                .filter(c -> c.state != ElevatorState.MAINTENANCE)                .min(Comparator.comparingInt(c -> Math.abs(c.floor - floor)));    }}
class ElevatorController {    private final List<Elevator> cars;    private final DispatchStrategy dispatcher;    private int tick = 0;
    ElevatorController(List<Elevator> cars, DispatchStrategy dispatcher) {        this.cars = cars;        this.dispatcher = dispatcher;    }
    void hallRequest(int floor) {        Optional<Elevator> car = dispatcher.choose(cars, floor);        car.ifPresent(c -> c.addStop(floor));        System.out.println("Hall call at " + floor + " -> car " + car.map(c -> c.id).orElse("none"));    }
    void cabinRequest(String carId, int floor) {        cars.stream().filter(c -> c.id.equals(carId)).findFirst().ifPresent(c -> c.addStop(floor));        System.out.println("Cabin " + carId + " -> " + floor);    }
    void run(int ticks) {        for (int i = 0; i < ticks; i++) {            tick++;            StringBuilder line = new StringBuilder("t" + tick + ":");            for (Elevator car : cars) {                if (car.state != ElevatorState.MAINTENANCE) line.append("  ").append(car.step());            }            System.out.println(line);        }    }}
public class ElevatorControllerDemo {    public static void main(String[] args) {        Elevator a = new Elevator("A", 0);        Elevator b = new Elevator("B", 5);        Elevator c = new Elevator("C", 4);        c.state = ElevatorState.MAINTENANCE;        ElevatorController controller = new ElevatorController(List.of(a, b, c), new NearestCar());
        controller.hallRequest(4);        controller.hallRequest(1);        controller.run(2);        controller.cabinRequest("B", 8);        controller.run(5);    }}
Output
Hall call at 4 -> car B
Hall call at 1 -> car A
t1:  A MOVING_UP to 1  B MOVING_DOWN to 4
t2:  A opens doors at 1  B opens doors at 4
Cabin B -> 8
t3:  A idle at 1  B MOVING_UP to 5
t4:  A idle at 1  B MOVING_UP to 6
t5:  A idle at 1  B MOVING_UP to 7
t6:  A idle at 1  B MOVING_UP to 8
t7:  A idle at 1  B opens doors at 8

What this code does

  • Car C sits on floor 4 but is in maintenance, so the hall call at 4 goes to B (1 floor away) and the call at 1 goes to A.
  • The controller only routes requests and runs ticks; each car decides its own moves in step(). That split keeps both classes small.
  • B picks up at 4, gets a cabin request for 8 and turns up. Cars with nothing to do report idle each tick.

The single-file design has four parts: ElevatorState, Elevator (floor, state, stops and step()), DispatchStrategy with its implementations, and ElevatorController.

In the demo output, look for the dispatcher skipping the car in maintenance and the busy car finishing its direction before turning.

Next step

Check your understanding

12 quick questions