LLD: Design an Elevator System
System Design · Low-Level Design · Intermediate · 25 min
Model an elevator as a state machine (idle, moving, doors open) with the State pattern, plug in a scheduling strategy (LOOK, the classic 'keep going while there is work ahead'), and code a tick-by-tick simulation that an interviewer can test.
A lift with a little brain that only ever asks two questions: 'is someone waiting on this floor?' and 'is there more work in the direction I am already going?'. If yes, it keeps going. Only when the work ahead runs out does it turn around.
The idea in everyday words
A bus on a long road. It drives in one direction, stopping wherever someone wants to get on or off. It does not turn around just because one person behind it waved. When nobody ahead needs it, it turns around and serves the other side. That is the LOOK algorithm. The bus driver also has moods: parked, driving, doors open. What the driver does next depends on the mood: that is the State pattern.
Requirements and a model you can test
Real elevators are complicated: weight sensors, emergency stops, many cars, fire mode. In the interview, simplify on purpose and say so.
Our model:
- One elevator, floors
0tofloors - 1. It starts at floor 0, idle, doors closed. - Two kinds of button: a hall call (
call 5, someone waiting on floor 5) and a cabin button (go 5, someone inside). Both just add floor 5 to the set of requests. - Time moves in ticks (
step). In one tick the elevator does exactly one thing: move one floor, open its doors, close its doors, or stay idle.
Why ticks? A tick-based simulation is deterministic: the same commands always give the same output. That makes it testable, which is what a machine-coding round wants. In real code you would drive the same step() from a timer.
| Question to ask | Our answer |
|---|---|
| One car or many? | One here; many in "Go deeper" |
| Do hall calls have a direction (up / down button)? | Not in our model; mention it as an extension |
| What does pressing an already-requested floor do? | Nothing new: it is one stop |
| Invalid floor? | error: no floor 12 |
The state machine
An elevator is a textbook state machine: what it does on the next tick depends on what it is doing now.
request elsewhere arrived at a requested floor
┌──────┐ ──────────────────► ┌────────┐ ─────────────────────────► ┌────────────┐
│ Idle │ │ Moving │ │ Doors open │
└──────┘ ◄──────┐ └────────┘ ◄───────────────────────── └────────────┘
▲ │ doors close, more requests │
│ └──────────────────────────────────────────────────────────┘
│ doors close, no requests left
└─ request on the current floor: open the doors straight away
| State | On each tick |
|---|---|
| Idle | Request on this floor → open doors. Other requests → ask the strategy for a direction and move. None → stay idle. |
| Moving | This floor is requested → open doors (a stop). Otherwise → move one more floor in the strategy's direction. |
| Doors open | This floor pressed again → stay open. Otherwise close the doors; next state is Moving if requests remain, else Idle. |
The State pattern turns each row into a small class with a step(elevator) method. The Elevator just calls self.state.step(self). Adding a "Maintenance" or "Fire mode" state is a new class, and no giant if state == ... block grows in Elevator.
When is an enum enough? With 2 or 3 states and simple rules, an enum plus one match is fine. Use State classes when each state has its own rules for several events (step, press, emergency) and the if blocks start to repeat.
Scheduling: which way next?
Choosing the next direction is a separate decision, so it lives in its own Strategy object. The four classic algorithms (the same ones disks use to move their read head):
| Strategy | Rule | Problem |
|---|---|---|
| FCFS (first come, first served) | Serve requests in the order pressed | Zig-zags up and down: lots of wasted travel |
| SSTF (shortest seek first) | Always go to the nearest request | A busy middle can starve far floors for a long time |
| SCAN ("elevator algorithm") | Go all the way to the end, then reverse | Wastes trips to empty top or bottom floors |
| LOOK | Keep going while there are requests ahead; reverse only when none are left | Our choice: efficient and fair |
LOOK in words: if I am going up and anyone above me is waiting, keep going up. Same for down. If I am idle and requests are on both sides, go to the nearest one (a tie goes up). Otherwise go to the side that has requests.
Tiny example. At floor 2, going up to 6, someone calls from floor 1 and from floor 4. FCFS would go 6 → 1 → 4. LOOK goes up: stops at 4, then 6, then comes down to 1. Count the floors: FCFS travels 4 + 5 + 3 = 12 floors from floor 2, LOOK travels 4 + 5 = 9.
def travel(start, stops):
total, here = 0, start
for s in stops:
total, here = total + abs(s - here), s
return total
print("FCFS:", travel(2, [6, 1, 4]))
print("LOOK:", travel(2, [4, 6, 1]))
Classes
Elevator
├─ floor, going ("up" | "down" | "idle")
├─ requests: set of floors (a set: two presses of 5 = one stop)
├─ state: ElevatorState (Idle | Moving | DoorsOpen)
├─ strategy: SchedulingStrategy (LOOK today; injected)
├─ press(floor) -> "queued 5" | error
└─ step() -> self.state.step(self)
ElevatorState <|── IdleState, MovingState, DoorsOpenState { step(elevator) }
SchedulingStrategy <|── LookStrategy { direction(floor, going, requests) }
Why a set for requests? Two people pressing 5 (one in the hall, one inside) still means one stop. A list would make the elevator open twice on floor 5.
Why does the strategy get going? LOOK needs to know the current direction to decide "is there work ahead?". When the elevator becomes idle, going resets to "idle", so the next decision is "nearest first" rather than an old direction.
Who owns what: the Elevator owns its state and requests. States change the elevator through small methods (open_doors, move), so no state reaches into another state's business.
Go deeper: many elevators, buttons from many threads, safety
- A building has many cars. Add a Dispatcher (also a Strategy) that assigns each hall call to one car. Simple and good: score each car by distance, with a bonus if it is already moving toward the call in the right direction, and a penalty for a full or out-of-service car. Big buildings use destination dispatch: you type your floor in the lobby, and the system groups people going to nearby floors into the same car.
- Hall calls with direction. A real hall has up and down buttons. Someone on floor 4 pressing "down" should not be picked up by a car going up past 4. Store requests as
(floor, direction)and only stop for matching ones (cabin buttons match both). - Concurrency. Buttons are pressed from many threads (or interrupts) while the control loop runs. Make the request set thread-safe (a lock, or a queue of button events that only the control loop thread reads). One controller thread per car that owns all state changes is the simplest safe design.
- Safety invariants. The car never moves with doors open. Put that rule in one place (the Moving state is entered only from a closed-doors state) and say it out loud: interviewers love invariants.
- Starvation. LOOK cannot starve a floor: in the worst case a request waits for one full sweep in each direction. SSTF can, which is the classic argument for LOOK.
Step by step
- Request and start moving:
Floors 0 to 9, car at 0. go 6 → 'queued 6'. step: idle, request above, LOOK says up → 'floor 1 up'. step → 'floor 2 up'.
- Calls behind and ahead:
call 1 (behind) and call 4 (ahead) are queued. Requests = {1, 4, 6}. Going up with work above, so LOOK keeps going up: 'floor 3 up', 'floor 4 up'.
- Stop at 4:
Floor 4 is requested: the Moving state opens the doors ('floor 4 doors open') and removes 4. Next tick the Doors-open state closes them: 'floor 4 doors closed'. Requests {1, 6} remain, so the state becomes Moving.
- Serve 6 first:
Still going up and 6 is above, so: 'floor 5 up', 'floor 6 up', 'floor 6 doors open', 'floor 6 doors closed'. The call from floor 1 waited, but the car never zig-zagged.
- Turn around:
Going up, nothing above 6 any more, but 1 is below: LOOK reverses. 'floor 5 down' ... 'floor 1 down', then 'floor 1 doors open', 'floor 1 doors closed'.
- Idle:
No requests left: after the doors close the state is Idle and going resets to idle. step → 'floor 1 idle'. Total travel: 2 → 6 → 1 is 9 floors from floor 2 (FCFS order 6, 1, 4 would be 12).
Code example
class Car:
def __init__(self, name, floor, going):
self.name, self.floor, self.going = name, floor, going
def score(car, call_floor): # lower is better
dist = abs(car.floor - call_floor)
if car.going == "idle":
return dist
heading_to_call = (car.going == "up" and car.floor <= call_floor) or \
(car.going == "down" and car.floor >= call_floor)
return dist if heading_to_call else dist + 20 # must turn around first
def dispatch(cars, call_floor): # a Dispatcher strategy for many cars
best = min(cars, key=lambda c: (score(c, call_floor), c.name))
return best.name
cars = [Car("A", 1, "up"), Car("B", 8, "down"), Car("C", 5, "idle")]
for call in [3, 6, 9, 0]:
print(f"call from {call}: send", dispatch(cars, call))Complexity
- Time: O(R) per tick to look at R pending requests (O(log R) with two sorted sets above and below)
- Space: O(R) for the request set, O(1) for the state
Interview tips
Simplify out loud: one car, ticks, a set of requested floors. Then list the extensions you are leaving out (many cars, direction buttons, weight limits).
Draw the state diagram first (Idle, Moving, DoorsOpen) and name the event on each arrow. It is the clearest 30 seconds of the interview.
Separate scheduling into a Strategy and compare FCFS, SSTF, SCAN and LOOK in one sentence each. Pick LOOK and say why (no starvation, no wasted trips).
State the safety invariant: never move with doors open. Show where your code guarantees it.
For 'many elevators', describe a Dispatcher that scores cars by distance and direction, and mention destination dispatch for big buildings.
Challenge: Elevator with States and LOOK Scheduling
Simulate one elevator, tick by tick. Write run_elevator(floors, ops): floors are numbered 0 to floors - 1, and the car starts at floor 0, idle, doors closed. Return one output line per command.
| Command | What it does | Output |
|---|---|---|
call <f> or go <f> |
Add floor f to the requests (a set: pressing twice is one stop) | queued <f>, or error: no floor <f> if f is outside the building |
step |
One tick (see below) | the car's action |
One tick, by state:
- Idle: if the current floor is requested → open the doors. Else if there are no requests →
floor <f> idle. Else move one floor (direction below). - Moving: if the current floor is requested → open the doors. Else move one floor.
- Doors open: if the current floor is requested again → open again (stay open). Else output
floor <f> doors closed; the next state is Moving if requests remain, otherwise Idle (and the direction resets to idle). - Open the doors = remove the current floor from the requests, output
floor <f> doors open, state becomes Doors open. - Move = pick a direction with LOOK, go one floor, output
floor <new f> uporfloor <new f> down.
LOOK: going up and any request above → up. Going down and any request below → down. Otherwise, if requests are on both sides (this happens when idle) → toward the nearest one, a tie goes up. Otherwise toward the side that has requests.
Example:
run_elevator(10, ["go 3", "step", "step", "step", "step", "step", "step"])
-> ["queued 3", "floor 1 up", "floor 2 up", "floor 3 up",
"floor 3 doors open", "floor 3 doors closed", "floor 3 idle"]
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- State pattern (Refactoring.Guru) (Easy)
- Strategy pattern, for swapping schedulers (Refactoring.Guru) (Easy)
More in Low-Level Design
- Low-Level Design: How to Approach the Round
- LLD: Design a Parking Lot
- LLD: Design a Rate Limiter (Classes and Strategies)
- LLD: Design Splitwise (Expense Sharing)
- LLD: Design Movie Ticket Booking (BookMyShow)
Previous: LLD: Design a Parking Lot · Next: LLD: Design a Rate Limiter (Classes and Strategies)