AlgoViz

Design an elevator system

medium 90 min

Model a bank of several cars that answer hall calls and car calls.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 5:05

Elevator system LLD in 90 seconds

1:26Reel coming soon

Design an elevator system in one picture
Design an elevator system in one picture

Theory

Read or listen first. About 2 min.

What it is

An elevator system in a low-level design round is the control software of one or more cars. It turns presses into promises (this car will come), promises into an order of stops, and the order into single steps of a motor and a door.

Underneath it are two classic problems. Choosing a car is assignment: match work to workers. Ordering stops is one-dimensional routing: visit points on a line with little travel and without forgetting anyone.

The answer is small: a bank, a car, a call and one rule. The difficulty is in what a stop means. A button inside is served whenever the car passes; a call from a floor only in its direction.

Why it exists

Everybody has waited for a lift and been angry at it. That makes it a good exercise: each person has requirements without reading a document.

It separates people who model nouns (floor, button, panel) from people who model decisions. The nouns are many and empty. The decisions are few and hard.

It has honest safety in it. Software with a motor must say what happens when it is wrong, and which rules it does not guard alone.

A short history

  1. 1852

    Elisha Otis introduces the safety elevator: if the cable breaks, the car does not fall. Otis shows it in New York in 1854.

  2. 1857

    On 23 March the first such passenger elevator is installed in a store at 488 Broadway, New York.

  3. 1880

    Werner von Siemens builds the first electric elevator in Germany.

  4. 1961

    Leo Port in Sydney proposes and patents destination dispatch. Relays are not ready for it; microprocessors make it possible from the late 1970s.

  5. 1968

    The first volume of Donald Knuth's The Art of Computer Programming simulates the elevator of a mathematics building. It is the earliest published treatment of the elevator algorithm.

Words to know

Hall call
A press on a floor: floor and direction.
Car call
A press inside a car: a target floor. Also cabin call.
Bank
A group of cars that share hall buttons.
Dispatcher
The rule that chooses a car for a hall call.
SCAN
Sweep to the end of the shaft, then back. The elevator algorithm.
LOOK
Like SCAN, but turn at the last stop ahead.
Dwell
How long doors stay open.
Interlock
A condition that makes a dangerous action impossible.
Nudging
Closing slowly with a buzzer after several obstacles.
Destination dispatch
People enter the target in the lobby and are sent to a car.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

Solve it like an interview

New to it? Start with Approach. Revising? Go straight to the mock.

  1. 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
  2. 2ScopeAsk what changes the design, then commit to a short list.
  3. 3API and dataThe contract first, then the data that serves it.
  4. 4DesignStart with the smallest system that works. Change it only when something breaks.
  5. 5Deep divesCompare the options before you open them, then say which you would pick.
  6. 6Explain your choicesAnswer first. Then compare your reasoning.
  7. 7By levelThe same question is judged differently for mid, senior and staff.
  8. 8MockAnswer against the clock, then score yourself.

How it works

Step through the idea, or press Play.

Step 1 of 3

Hall call. A person on a floor asks for up or down; the dispatcher assigns the most suitable car

Understand it

Start here

The lighthouse with two buckets

A lighthouse keeper lifts oil, bread and letters with two buckets, each on its own rope. There are five levels and one bell on each. Watch three things: who decides which bucket comes, who decides where it stops, and why the direction of a call must not be forgotten.

One morning at the lighthouse lift
12345ABMAX'S BOARDquiet

Two decisions, choose and drive. Keep them in two classes and the rest of this problem becomes small.

What an interviewer looks for here

  • Two kinds of call

    A hall call has a direction, a car call has a target. Mixing them is the most common mistake.

  • Choose and drive apart

    Which car comes is a rule that changes. How a car moves is mechanics that does not.

  • A clear turn rule

    Go on while there is work ahead, then turn. Nobody waits forever.

  • Doors are not decoration

    The car never moves with open doors. Say where this rule lives.

Questions

Six questions, and what each answer changes

AskIf the answer isThen
How many floors and cars?10 floors, 2 carsSimple loops are fast enough. Say so
Up and down buttons, or a target in the lobby?Up and downHall calls with a direction. A target in the lobby is another design, see the Destination dispatch page
Is there a weight limit?Not todayA car always takes everybody. Name the place where a limit would go
Emergencies?Fire alarmA mode that overrides stops. Later, not in the first code
Doors blocked by people?A timer is enoughA count of ticks. With sensors, Door becomes a class
One thread or many?A simulationstep() moves the world by one tick. Real buttons come from other threads: FAANG page 1
A tick is our unit of time: one floor of travel, or one unit of open doors. Real seconds come later, as a number.

One trip, from the button to the empty car

Two calls

Hall call and car call

Hall callCar call
PressedOn a floor, outsideInside a car
CarriesFloor and directionTarget floor only
Who serves it?Any car: the dispatcher choosesThis car, nobody else
DirectionMust be saidFollows from where the car is
Can be moved to another car?Yes, until it is servedNever: the person is inside
In the codeHallCall(5, DOWN)car.press(1), a number in a set

Should this car open here?

The last question is the one people forget. A car that goes up to fetch somebody who wants to go down must open there, because it turns there.

Design, first try

The design most people draw first

The design to avoid: a class for every noun, and the direction is lost

Building- instance: Building+ getInstance(n, k)ElevatorController- pending: Queue+ requestElevator()- calculateCost()+ step()

1/4A global building

getInstance(10, 2) the first time, getInstance(40, 8) the second time, and the second answer is the first building. The arguments are ignored in silence.

owns (dies together)usesimplementshas (lives on)extends (is a)

Nine boxes, and the one fact that matters most, where the person wants to go, has no home.
Python
class Elevator:    def __init__(self, floor):        self.floor, self.up_stops, self.down_stops = floor, set(), set()    def add_stop(self, floor):                 # the direction of the call is not even a parameter        if floor > self.floor:            self.up_stops.add(floor)        elif floor < self.floor:            self.down_stops.add(floor)    def go_up(self):        self.floor += 1        if self.floor in self.up_stops:            self.up_stops.remove(self.floor)            print("doors open at", self.floor)lift = Elevator(1)lift.add_stop(9)                               # somebody inside wants 9lift.add_stop(5)                               # on floor 5 somebody pressed DOWNfor _ in range(8):    lift.go_up()lift.add_stop(9)                               # pressed again while standing at 9print(lift.up_stops, lift.down_stops)
Two bugs in one run. The doors open at 5 on the way up and the call is erased, so the person who wanted down rides up or waits for nobody. And a press on the current floor disappears.
Edit and run it in your browser

Design, better

The design to reach

The design to reach: one bank, independent cars, one rule for choosing

Car+ id: String+ floor: int- cabin: Set<int>- hall: Set<HallCall>- openFor: int+ press(floor)+ accept(call)+ step(): HallCall?+ ticksTo(call): int«enum»CarStateIDLE, MOVINGDOORS_OPEN

1/5Start with the car

A car has a floor, a direction and stops. It has two kinds of stop, because they mean different things: a button inside (cabin) and a call from a floor (hall).

owns (dies together)usesimplementsdepends onhas (lives on)

Floors, buttons, panels and displays are missing on purpose. The Entities page says why.

What each class owns

ClassKnowsDoesDoes not know
BankCars, floors, who promised whatChecks buttons, assigns, switches lampsHow a car moves
CarIts floor, direction, stops, door timerOne tick, estimates its own arrivalOther cars, lamps
DispatcherNothing between callsPicks one car for one callDoors, stops, people
HallCallFloor and directionNothing: a valueWhich car will come

Order

FCFS, SCAN and LOOK

Ten people press ten buttons. In which order should one car visit the floors? The question is older than most computers, and it is the same question a disk arm has. The elevator algorithm (SCAN) was named after lifts, not the other way round.

RuleTurnsFloors travelled for 10 random stops out of 20 floorsTrouble
First come, first servedWhenever the next call is the other way69.8Runs past people who wait
SCANAt the top and bottom of the building26.1Goes to floors nobody asked for
LOOKAt the last stop ahead24.7Must look ahead, one line of code
Nearest stop firstWhenever the nearest is the other wayOften shortStarves far floors: a busy middle keeps it
Our own simulation: one car, random start, 10 different stops known at the start, 2,000 rounds, first sweep up. Your numbers will differ, the order will not.

Car at 5, going up, with calls at 8, 3 and 7

LOOK: 3 up and 5 down, 8 floors. SCAN in a 10 floor building: 12. In the order of the buttons 8, 3, 7: 3 + 5 + 4 = 12.

States

The life of a car

Three states, and no arrow from moving to moving with open doors

Up and down are not states. They are a direction the car has in any state: a car with open doors still knows which way it will go.

The life of a hall call

The other decision

Which car should come?

How does the dispatcher compare two cars?

BreaksDistance
How
abs(car.floor - call.floor)
Limit
A car one floor away that is leaving in the other direction wins, and comes back after a full tour.
Choose when
One car, or a first sketch.
WorksDistance plus a penalty
How
Add 100 if the car would have to turn.
Limit
It does not see stops. A car 7 floors away with 6 stops on the way beats an idle car at distance 8, although it needs 26 ticks against 9.
Choose when
A fair answer for the first 30 minutes. Say what it ignores.
StrongAsk the car how long it would take
How
Copy the car, add the call, run step() on the copy until the call is served, count.
Limit
More work: at most a few hundred small steps per car. And it knows only what is known now.
Choose when
Here. The estimate can never disagree with the real movement, because it is the movement.

The third option is worth a pause. A formula for the arrival time must know every rule of the car: turning, doors, promises. Write it and you have the rules twice. Running the real rules on a copy keeps them in one place.

Summary

The whole topic in one minute.

A bank remembers which car promised which call. A dispatcher chooses, a car drives. The car holds cabin floors and hall calls apart, goes on while there is a stop ahead, then turns, and opens for the other direction only where it turns.

One tick does one thing: open, wait or move. The wait comes before the move, and that line is the interlock. Estimates run on a copy of the car. Modes come before stops, threads talk through one inbox.

  • Hall call: floor and direction. Car call: floor only. Keep them apart inside the car.
  • A dispatcher chooses, a car drives, a bank remembers promises and lamps.
  • LOOK: go on while there is a stop ahead, then turn. Never go to floors nobody asked for.
  • A car opens for its own direction, and for the other one only where it turns.
  • Moving and open doors exclude each other in one place of the code.
  • State is derived from direction and door timer, so it cannot disagree with them.

Sources