Design an Elevator System
🛗 What is an elevator system? It is the controller behind a bank of elevators. When someone presses the call button on a floor, it decides which car goes there. When someone inside a car presses a floor button, it adds that floor to the car's trip. Then it moves every car, one floor at a time, in an order that serves everyone without wasting trips.
Interviewers ask this problem under a few names: "design an elevator", "manage the elevators of a building", "dispatch elevator requests", or "implement the SCAN algorithm for an elevator". They are one design with three layers. The system manages the cars and takes requests. A dispatcher decides which car answers a call from a floor. Each car decides the order of its own stops, and that is where SCAN lives. We build all three.
The elevator is a favorite because the classes are easy to name, but the behavior is not. The interviewer is watching whether you pin down exactly when a car turns around, whether your dispatch rule is consistent with how the cars really move, and whether you can explain why the naive orderings fail.
Requirements
"Design an elevator system for a building with several elevators. People call an elevator from a floor and choose their destination inside."
That leaves almost everything open. Which car goes? In what order does a car visit its floors? What does "time" even mean here? The questions below settle the decisions that change the code.
Clarifying Questions
You: How many elevators and floors? Is it one building?
Interviewer: One building, a configurable number of elevators and floors. Floors are numbered from 0. Every car starts at floor 0, empty and idle.
You: The call buttons on each floor usually have up and down arrows. Does the direction matter?
Interviewer: Keep it simple for now: a call is just a floor that some car must visit. A car stops at every floor on its list, whichever way it is going. We may come back to directions later.
You: When a car has several floors to visit, in what order does it go?
Interviewer: It should not zigzag up and down, and nobody should wait forever. You choose the algorithm, but explain why.
You: How do we pick which car answers a call from a floor?
Interviewer: The one that would get there first. If two cars tie, take the lower-numbered one.
You: How does time work? Should the cars move on a real clock?
Interviewer: Use a simulation step. In each step every moving car travels one floor. Stopping at a floor does not cost an extra step.
You: Do we model doors, weight limits, emergency stops?
Interviewer: Not now. Focus on requests, dispatching and movement.
The answer about directions is the one to write down. With direction-aware calls, a car going up skips someone who wants to go down, and the stop list becomes more complex. Asking it early keeps the core design small, and it gives you a ready-made follow-up for the end of the interview.
💡 Interview tip: Ask for a step-based clock. "Each step moves every car one floor" turns a fuzzy real-time problem into a deterministic one: you can trace it on the whiteboard, and every method becomes easy to test. The practice tests here work the same way.
Final Requirements
- The building has
Nelevators (ids0toN - 1) andFfloors (0toF - 1). Every elevator starts at floor 0, idle. - A call from a floor is assigned to one elevator, which adds that floor to its stops. The system reports which elevator was chosen.
- A button pressed inside an elevator adds that floor to its stops.
- Calls and buttons for floors or elevators that do not exist are rejected.
- Time moves in steps. In each step, every elevator that has stops moves one floor, and stops at a floor on its list when it reaches it.
- Each elevator visits its stops without zigzagging: it keeps going in one direction while it has stops ahead, and only then turns around. No stop waits forever.
- A call goes to the elevator that would reach the floor in the fewest steps; ties go to the lowest id.
- Anyone can ask an elevator's current floor and direction (
UP,DOWNorIDLE), for the displays in the lobby. - The dispatching rule is likely to change (energy saving, rush-hour modes), so changing it must not touch the elevators.
Out of scope
- Up and down call buttons with direction-aware stopping (covered in Extensibility).
- Doors, door timers, capacity and weight limits.
- Emergency stop, fire mode and maintenance (one of these comes back in Extensibility).
- Real-time clocks and hardware signals.
Entities and Relationships
Go through the requirements and keep the nouns that hold state or make decisions.
- ElevatorSystem: the entry point. It owns the elevators and the dispatcher, checks every request, and advances time.
- Elevator: one car. It knows its floor, its direction and its set of stops, and it decides how to move. All of requirement 5 and 6 lives here.
- Dispatcher: the rule that picks an elevator for a call. It is its own entity because requirement 9 says it will change.
- Direction:
UP,DOWNorIDLE. An enum.
Several nouns from the prompt are not classes in this design:
- Request is just a floor number. A call from floor 5 and a button for floor 5 in the same car mean the same thing: "this car must visit 5". Once a call has been assigned, there is nothing left to remember about where it came from, so a set of integers is the whole model.
- Floor has no state of its own here. It is an integer.
- Button, Door and Display are hardware or callers. Buttons call the system's methods, the display reads
get_status, and doors are out of scope.
Who owns whom:
| Owner | Owns | How many |
|---|---|---|
| ElevatorSystem | Elevator | one per car |
| ElevatorSystem | Dispatcher | exactly one, swappable |
| Elevator | stops (set of floors) | zero or more |
| Elevator | Direction | exactly one at a time |
Class Design
We go top down. The orchestrator validates requests and hands them over; it should never contain movement rules or dispatch math.
ElevatorSystem
The orchestrator. It answers the four requests from the outside world: a call from a floor, a button inside a car, a time step, and a status query.
class ElevatorSystem:
elevators: List[Elevator] # requirement 1
num_floors: int # requirement 4: to validate floors
dispatcher: Dispatcher # requirement 9: injected, so it can be swapped
def __init__(self, num_elevators: int, num_floors: int, dispatcher: Optional[Dispatcher] = None): ...
def call_elevator(self, floor: int) -> int: ... # elevator id, or -1
def select_floor(self, elevator_id: int, floor: int) -> bool: ...
def step(self) -> None: ...
def get_status(self, elevator_id: int) -> str: ... # "3 UP", or ""
call_elevator returns the chosen id because the lobby display shows "go to elevator B". The elevators sit in a list indexed by id, so checking an id is a range check and finding the car is one index.
Elevator
One car, and the class where the real logic lives.
class Elevator:
elevator_id: int
floor: int # where it is now
direction: Direction # where it will move on the next step
stops: Set[int] # floors it still has to visit
def add_stop(self, floor: int) -> None: ...
def step(self) -> None: ... # requirement 5
def eta(self, floor: int) -> int: ... # requirement 7: steps to reach a floor
def status(self) -> str: ... # requirement 8
stops is a set because a floor pressed twice is still one stop, and because a car never needs its stops in arrival order (we will see why that order is the wrong one). direction means "where I will move next", which gives it one clear meaning at every moment, including right after a new stop is added.
eta might look like it belongs in the dispatcher. It is here because only the car knows its movement rule. If we ever change how a car moves, its eta changes with it in the same class, and no dispatcher can go out of sync.
Direction
class Direction(Enum):
UP = "UP"
DOWN = "DOWN"
IDLE = "IDLE"
Dispatcher
class Dispatcher:
def choose(self, elevators: List[Elevator], floor: int) -> Elevator: ...
class EtaDispatcher(Dispatcher):
def choose(self, elevators: List[Elevator], floor: int) -> Elevator: ... # fastest arrival
A one-method interface with one implementation today, which is the Strategy pattern. It earns its place because the interviewer told us dispatching will change (requirement 9). The dispatcher only reads the elevators; adding the stop stays in ElevatorSystem, so a dispatcher cannot leave a car half updated.
Implementation
We start with the small pieces (adding a stop), then the two real decisions: in what order a car visits its stops, and which car gets a call. The second depends on the first, so the order matters.
Taking requests
Both kinds of request end in add_stop. The system checks the arguments first:
def call_elevator(self, floor: int) -> int:
if not self._valid_floor(floor): # requirement 4
return -1
elevator = self.dispatcher.choose(self.elevators, floor)
elevator.add_stop(floor)
return elevator.elevator_id
def select_floor(self, elevator_id: int, floor: int) -> bool:
if not 0 <= elevator_id < len(self.elevators) or not self._valid_floor(floor):
return False
self.elevators[elevator_id].add_stop(floor)
return True
Inside the car, one case needs care: a request for the floor the car is already on.
def add_stop(self, floor: int) -> None:
if floor == self.floor:
return # already here: the doors open, nothing to add
self.stops.add(floor)
self._update_direction()
If we added the current floor as a stop, the car would have to leave and come back to "reach" it, or worse, a moving car would remember a stop it is already standing on. Treating it as served at once keeps the invariant simple: a car never has its own floor as a stop. _update_direction is the turning rule, which we build next.
In what order does a car visit its stops?
This is the heart of the problem and the place interviewers push hardest. Picture one car at floor 0 in a 10-floor building, with stops requested in this order: 9, 1, 8, 2.
Bad Solution: first come, first served
Approach
Keep the stops in a queue and always drive to the oldest one.
class Elevator:
def __init__(self, elevator_id: int):
self.floor = 0
self.queue: Deque[int] = deque()
def step(self) -> None:
if not self.queue:
return
target = self.queue[0]
self.floor += 1 if target > self.floor else -1
if self.floor == target:
self.queue.popleft()
Challenges
It is fair, but the car goes 0 → 9 → 1 → 8 → 2: that is 9 + 8 + 7 + 6 = 30 floors, while a sensible route needs 9. Worse, it drives past floor 1 on the way to 9 and does not stop, because 1 is not at the front of the queue. Real buildings would never accept this. It is still worth saying out loud, because it shows you know that arrival order is the wrong order for a moving machine.
Good Solution: nearest stop first
Approach
At every step, head for the closest stop. This is the elevator version of SSTF (shortest seek time first), a classic disk-scheduling rule.
def step(self) -> None:
if not self.stops:
return
target = min(self.stops, key=lambda s: (abs(s - self.floor), s))
self.floor += 1 if target > self.floor else -1
self.stops.discard(self.floor)
Challenges
Our example now goes 0 → 1 → 2 → 8 → 9: just 9 floors. But nearest-first has a nasty failure called starvation. Imagine the car near the bottom of a busy building, with people on floors 1 to 3 pressing buttons all the time. Someone on floor 9 is always the farthest stop, so the car never goes up. Requirement 6 says no stop waits forever, and this rule cannot promise that. It also changes direction whenever a new request appears behind it, which riders experience as the car "changing its mind".
Great Solution: SCAN (keep going while there are stops ahead)
Approach
Do what real elevators do. Pick a direction and keep moving in it, stopping at every requested floor on the way, as long as there is a stop ahead. When nothing is left ahead, turn around and sweep the other way. This is the SCAN algorithm, also called the elevator algorithm. Strictly, SCAN sweeps all the way to the top or bottom floor before turning; the variant that turns at the last requested stop is called LOOK. LOOK is what everyone means in an elevator interview, and it is what we build.
The whole rule fits in one method that runs after every change:
def _update_direction(self) -> None:
above = any(s > self.floor for s in self.stops)
below = any(s < self.floor for s in self.stops)
if self.direction == Direction.UP and above:
return # keep going up
if self.direction == Direction.DOWN and below:
return # keep going down
if above:
self.direction = Direction.UP # turn around (or start) toward the stops
elif below:
self.direction = Direction.DOWN
else:
self.direction = Direction.IDLE # nothing left to do
And moving is now trivial, because the direction already says where to go:
def step(self) -> None:
if self.direction == Direction.IDLE:
return
self.floor += 1 if self.direction == Direction.UP else -1
self.stops.discard(self.floor) # stop here if it was asked for
self._update_direction()
Challenges
The example route is 0 → 1 → 2 → 8 → 9 again, 9 floors, and it stays efficient under load. Starvation is gone: a stop is reached within at most two sweeps, because the car only turns around when nothing is left ahead, and it never turns away from a stop that is in front of it. A rider who has just got in also never sees the car reverse while their floor is still ahead.
There is one subtle point in _update_direction: the first two checks only keep the current direction. A car going up with stops both above and below keeps going up, even if the stop below is much closer. That is exactly what prevents zigzagging. An idle car can only ever get one stop at a time (it gets a direction the moment the first stop arrives), so the "start toward the stops" branch never has to choose between two sides.
The sets make the any(...) checks linear in the number of stops. With at most a few dozen floors that costs nothing. In Java and C++ the reference solutions keep stops in a sorted set (TreeSet, std::set), so "is there a stop above?" is a single higher() or upper_bound() call.
⚠️ Common mistake: Using the State pattern with an
IdleState,MovingUpStateandMovingDownStateclass here. The three states differ only in a sign (+1,-1,0) and one comparison, so the classes would each hold two lines. An enum plus one rule method is clearer. States become worth classes when they behave very differently, for example a maintenance mode that ignores requests, or doors that must close before moving.
Which car answers a call?
Now the dispatcher. Take two cars in a 30-floor building: car 0 is at floor 8 going up to 20, and car 1 is at floor 3 going up to 6, with a stop at 0 waiting for its trip back down. A call comes from floor 10.
Bad Solution: always the same car, or round robin
Approach
Send every call to car 0, or rotate through the cars.
class RoundRobinDispatcher(Dispatcher):
def __init__(self):
self.next_index = 0
def choose(self, elevators: List[Elevator], floor: int) -> Elevator:
elevator = elevators[self.next_index % len(elevators)]
self.next_index += 1
return elevator
Challenges
Round robin spreads calls evenly but ignores where the cars are. If it is car 1's turn, the person on floor 10 waits 7 steps for car 1, when car 0 passes floor 10 in 2. Mention it only to set up the real question: what does "best car" mean?
Good Solution: the nearest car
Approach
Pick the car whose current floor is closest to the call.
class NearestDispatcher(Dispatcher):
def choose(self, elevators: List[Elevator], floor: int) -> Elevator:
return min(elevators, key=lambda e: (abs(e.floor - floor), e.elevator_id))
Challenges
Better, and it gets the floor 10 call right (car 0 is 2 floors away, car 1 is 7). Now try a call from floor 7 instead. Car 0 is 1 floor away, so it wins, but it is moving away. Under SCAN it goes up to 20 and comes back: 12 + 13 = 25 steps. Car 1, at 3 going up, arrives in 4 steps. Distance alone ignores direction, and with SCAN cars, direction is most of the story.
Great Solution: the car that would arrive first
Approach
Ask each car how many steps it would need to reach the floor if the floor were added to its stops now, and pick the smallest. Since each car moves by SCAN, this number can be computed exactly from its floor, direction and stops:
- Idle: it drives straight there,
|floor - position|steps. - Moving toward the floor (going up and the floor is at or above it, or going down and the floor is at or below it): it reaches the floor on this sweep, again
|floor - position|steps. Stops on the way cost nothing extra in our model. - Moving away from the floor: it finishes the sweep to its farthest stop, turns, and comes back.
def eta(self, floor: int) -> int:
if self.direction == Direction.IDLE:
return abs(floor - self.floor)
if self.direction == Direction.UP:
if floor >= self.floor:
return floor - self.floor
top = max(self.stops) # finish the sweep up, then come back down
return (top - self.floor) + (top - floor)
if floor <= self.floor:
return self.floor - floor
bottom = min(self.stops) # finish the sweep down, then come back up
return (self.floor - bottom) + (floor - bottom)
class EtaDispatcher(Dispatcher):
def choose(self, elevators: List[Elevator], floor: int) -> Elevator:
return min(elevators, key=lambda e: (e.eta(floor), e.elevator_id))
Challenges
This is consistent with how the cars really move, which is the property interviewers look for: the dispatcher's estimate and the car's behavior come from the same rule, in the same class. max(self.stops) is safe in the "moving away" branches, because a moving car always has at least one stop in its direction. That is the invariant _update_direction keeps. The tuple (eta, elevator_id) is the tie-break from requirement 7, and it makes results deterministic.
Be ready to name the weakness: an ETA rule only looks at the next call. It happily gives every call to the one car that is already heading that way, and leaves the others idle. That is efficient for a single rider but can make that car stop at every floor. Real controllers add a penalty per existing stop, or balance load across cars. With the dispatcher behind an interface, that is a new class and nothing else changes; see /low-level-design/strategy-pattern.
💡 Interview tip: When you present a cost formula, test it on one "moving away" case at the whiteboard. It is the case people get wrong, and walking through it shows the interviewer you understand how your own movement rule behaves.
Advancing time and reporting status
The rest is short. A step moves every car, and status is a formatted string.
def step(self) -> None:
for elevator in self.elevators:
elevator.step()
def get_status(self, elevator_id: int) -> str:
if not 0 <= elevator_id < len(self.elevators):
return ""
return self.elevators[elevator_id].status() # e.g. "3 UP"
Cars do not interact with each other during a step, so the order of the loop does not matter. That independence is also what makes concurrency easy to reason about later.
Edge cases
Go through these before you call the design done:
- Request for the floor the car is on: served at once, no stop added. A call from floor 0 at the start returns elevator 0, which stays idle.
- Duplicate stops: the set ignores them, so a floor pressed twice is visited once.
- Stop behind a moving car: added to the set, but the direction does not change until nothing is left ahead.
- Invalid floor or elevator:
call_elevatorreturns-1,select_floorreturnsFalse,get_statusreturns"". Nothing changes. - Step while idle: the car stays put.
- All cars tie: the lowest id wins, so the first call in a fresh building always goes to elevator 0.
Verification
Let's trace the first practice test: 2 elevators, 10 floors. "E0" is elevator 0.
| # | Call | What happens | Returns |
|---|---|---|---|
| 1 | call_elevator(5) |
Both idle at 0, ETA 5 each; tie goes to E0. E0 turns UP | 0 |
| 2 | step(), step() |
E0 moves to 2 | |
| 3 | call_elevator(3) |
E0 (2, UP, toward 3): ETA 1. E1 (0, idle): 3 | 0 |
| 4 | call_elevator(1) |
E0 moving away: (5 - 2) + (5 - 1) = 7. E1: 1. E1 turns UP | 1 |
| 5 | step() |
E0 reaches 3, removes it, keeps UP (5 ahead). E1 reaches 1, goes IDLE | |
| 6 | get_status(0), get_status(1) |
"3 UP", "1 IDLE" |
|
| 7 | select_floor(1, 0), select_floor(0, 8) |
E1 turns DOWN. E0's stops are {5, 8} | True, True |
| 8 | step() × 3 |
E0: 4, 5 (stop), 6. E1: 0 (stop), IDLE | |
| 9 | get_status(0) |
Still has 8 ahead | "6 UP" |
| 10 | call_elevator(2) |
E0 moving away: (8 - 6) + (8 - 2) = 8. E1: 2 | 1 |
| 11 | step() × 2 |
E0: 7, 8 (stop), IDLE. E1: 1, 2 (stop), IDLE | |
| 12 | get_status(0), get_status(1) |
"8 IDLE", "2 IDLE" |
|
| 13 | call_elevator(10), select_floor(2, 3) |
No floor 10, no elevator 2 | -1, False |
Step 4 is the one to point at in an interview. E0 is only one floor from floor 1, so a nearest-car rule would pick it, and the rider would wait 7 steps instead of 1.
Complete Code
Here is the full design in each language, the same code the practice tests run against.
from enum import Enum
from typing import List, Optional, Set
class Direction(Enum):
UP = "UP"
DOWN = "DOWN"
IDLE = "IDLE"
class Elevator:
"""One car. It moves with the SCAN rule (the LOOK variant): keep going while there are stops ahead."""
def __init__(self, elevator_id: int):
self.elevator_id = elevator_id
self.floor = 0
self.direction = Direction.IDLE
self.stops: Set[int] = set()
def add_stop(self, floor: int) -> None:
if floor == self.floor:
return # already here: the doors open, nothing to add
self.stops.add(floor)
self._update_direction()
def step(self) -> None:
if self.direction == Direction.IDLE:
return
self.floor += 1 if self.direction == Direction.UP else -1
self.stops.discard(self.floor) # stop here if it was asked for
self._update_direction()
def eta(self, floor: int) -> int:
"""Steps until this car reaches `floor`, if the floor were added as a stop now."""
if self.direction == Direction.IDLE:
return abs(floor - self.floor)
if self.direction == Direction.UP:
if floor >= self.floor:
return floor - self.floor
top = max(self.stops) # finish the sweep up, then come back down
return (top - self.floor) + (top - floor)
if floor <= self.floor:
return self.floor - floor
bottom = min(self.stops) # finish the sweep down, then come back up
return (self.floor - bottom) + (floor - bottom)
def status(self) -> str:
return f"{self.floor} {self.direction.value}"
def _update_direction(self) -> None:
# Keep the direction while there is a stop ahead; otherwise turn around, or go idle.
above = any(s > self.floor for s in self.stops)
below = any(s < self.floor for s in self.stops)
if self.direction == Direction.UP and above:
return
if self.direction == Direction.DOWN and below:
return
if above:
self.direction = Direction.UP
elif below:
self.direction = Direction.DOWN
else:
self.direction = Direction.IDLE
class Dispatcher:
def choose(self, elevators: List[Elevator], floor: int) -> Elevator:
raise NotImplementedError
class EtaDispatcher(Dispatcher):
"""The car that would arrive first; ties go to the lowest id."""
def choose(self, elevators: List[Elevator], floor: int) -> Elevator:
return min(elevators, key=lambda e: (e.eta(floor), e.elevator_id))
class ElevatorSystem:
def __init__(self, num_elevators: int, num_floors: int, dispatcher: Optional[Dispatcher] = None):
self.elevators = [Elevator(i) for i in range(num_elevators)]
self.num_floors = num_floors
self.dispatcher = dispatcher or EtaDispatcher()
def call_elevator(self, floor: int) -> int:
if not self._valid_floor(floor):
return -1
elevator = self.dispatcher.choose(self.elevators, floor)
elevator.add_stop(floor)
return elevator.elevator_id
def select_floor(self, elevator_id: int, floor: int) -> bool:
if not 0 <= elevator_id < len(self.elevators) or not self._valid_floor(floor):
return False
self.elevators[elevator_id].add_stop(floor)
return True
def step(self) -> None:
for elevator in self.elevators:
elevator.step()
def get_status(self, elevator_id: int) -> str:
if not 0 <= elevator_id < len(self.elevators):
return ""
return self.elevators[elevator_id].status()
def _valid_floor(self, floor: int) -> bool:
return 0 <= floor < self.num_floors
Try it yourself: the Practice button above runs your code against the same interface.
Extensibility
These are the follow-ups interviewers ask most once the base design runs. For each one, say which classes change and which stay the same.
1) How would you make the up and down call buttons matter?
Real hall buttons carry a direction, and a car going up should not stop for someone who wants to go down. Now a stop is not just a floor: the car must know why it is stopping. Split the stops into three sets.
class Elevator:
car_stops: Set[int] # buttons inside: always stop
up_calls: Set[int] # hall calls going up: stop only while moving up
down_calls: Set[int] # hall calls going down: stop only while moving down
def should_stop(self, floor: int) -> bool:
if floor in self.car_stops:
return True
if self.direction == Direction.UP:
return floor in self.up_calls or self._is_turning_point(floor)
return floor in self.down_calls or self._is_turning_point(floor)
The turning point matters: a down call at the top of an upward sweep is served when the car turns there. step uses should_stop, _update_direction looks at all three sets, and eta gets a slightly longer formula (a call in the opposite direction is only "on the way" after the turn). call_elevator takes a direction argument. The system class, the dispatcher interface and the tests' structure stay the same, which shows the boundaries were in the right place.
2) How would you take an elevator out of service?
A car under maintenance must not get new calls, and its pending stops must go somewhere. That is a new mode with different behavior, which is where the State pattern, or at least a mode field, starts to earn its keep.
class Elevator:
in_service: bool = True
class EtaDispatcher(Dispatcher):
def choose(self, elevators: List[Elevator], floor: int) -> Elevator:
candidates = [e for e in elevators if e.in_service]
return min(candidates, key=lambda e: (e.eta(floor), e.elevator_id))
# ElevatorSystem
def set_out_of_service(self, elevator_id: int) -> None:
car = self.elevators[elevator_id]
car.in_service = False
for floor in car.take_hall_calls(): # hand its waiting hall calls to other cars
self.call_elevator(floor)
take_hall_calls needs the car to know which stops came from hall calls. Our base design forgets that (a stop is just a floor), so this follow-up is a reason to keep hall calls in their own set; with the direction-aware calls from follow-up 1, they already are. Ask what happens to riders already inside: usually the car finishes its car stops and then parks. Also decide what call_elevator returns when no car is in service (-1 fits the existing error style). See /low-level-design/state-pattern for when a mode should become its own class.
3) How would you support express elevators that only serve some floors?
Tall buildings split cars into zones: some serve floors 0 to 20, others 0 and 21 to 40. Give each car the set of floors it serves, and filter in two places.
class Elevator:
served_floors: Set[int]
def serves(self, floor: int) -> bool:
return floor in self.served_floors
# EtaDispatcher.choose: only cars that serve the floor
candidates = [e for e in elevators if e.serves(floor)]
# ElevatorSystem.select_floor: reject buttons the car does not have
if not car.serves(floor):
return False
The movement rule does not change at all, because SCAN works on whatever stops a car has. The dispatcher filters candidates, and the system validates buttons. A destination dispatch system, where riders enter their destination in the lobby before boarding, is the bigger version of this idea: the dispatcher then picks a car for a (from, to) pair, which needs a new dispatcher and an ETA that includes the second leg.
4) How would you run it in real time with buttons pressed concurrently?
In a real controller, button presses arrive on many threads while a timer thread calls step. Two presses can both read a car's stops and direction while a step is changing them: a classic race on shared state. There are two standard answers.
The simplest is one lock around every public method of ElevatorSystem. Every operation is a handful of set and integer updates, so the lock is held for microseconds.
class ElevatorSystem:
def __init__(self, num_elevators: int, num_floors: int):
...
self._lock = threading.Lock()
def call_elevator(self, floor: int) -> int:
with self._lock:
return self._call_elevator(floor) # the code from above
def step(self) -> None:
with self._lock:
for elevator in self.elevators:
elevator.step()
A lock per car sounds faster, but dispatching reads every car's state to compare ETAs, so it would need all the locks at once, in a fixed order to avoid deadlock, for no real gain. The other common design is a single controller thread that owns all the state and reads requests from a queue: button threads only enqueue, and the controller applies requests and steps in order. It needs no locks on the cars at all, and it is how many embedded controllers work. See /low-level-design/race-conditions-and-locks for the lock details.
💡 Interview tip: If you pick the single-lock answer, name the race first (a call is dispatched using a car's position while a step is moving that car), then say why the coarse lock is enough. Interviewers want the reasoning more than the finest-grained design.
What is Expected at Each Level?
Junior
A junior candidate should identify the system, the elevator and the direction, take requests from floors and from inside the car, and move a car one floor per step. Starting with a first-come-first-served queue is fine if they can trace why it zigzags once the interviewer points it out, and then move to "keep going in one direction". The interviewer will usually help with the dispatch rule.
Mid-level
A mid-level candidate asks about directions, timing and tie-breaking before coding, and implements SCAN (LOOK) with a clear turning rule. They keep stops in a set, handle the current-floor and duplicate-stop cases, and put dispatching behind an interface. Their dispatcher considers direction, not just distance, and they can explain starvation and why SCAN avoids it.
Senior
A senior candidate does all of that quickly and makes the pieces consistent: the dispatcher's ETA comes from the same movement rule the car uses, and they can state the invariant that makes it correct (a moving car always has a stop ahead). They know the limits of their choices, such as an ETA rule piling calls onto one car, and how load-aware dispatching would fix it. On follow-ups they split stops by call direction, add service modes and zones without touching the movement rule, and choose between a single lock and a controller thread with a clear reason.