Design an elevator system
medium 90 minModel a bank of several cars that answer hall calls and car calls.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Cars, calls and promises: watch who decides, what moves, and which line did it.
Operations
A hall call
From a button to a promise: check, pick, accept, remember.
Step 1 of 6
Somebody presses down on 5
A rests at 1, B rests at 7. No lamp is lit.
Step 1: Somebody presses down on 5
def call(self, floor, direction): call = HallCall(floor, direction) if floor not in self._floors or floor + direction not in self._floors or not direction: raise ValueError(f"no such button: {call}") if call in self._owner: return car = self._dispatcher.pick(call, list(self._cars.values())) car.accept(call) self._owner[call] = car- Cost
- cars x ticks
- Guarantee
- One call, one car
A lit lamp is a key in the bank's map.
In the real world
The same elevator system doing real jobs. Pick one and step through it.
Floor 5, down, to the lobby. Two cars at 1.
Step 1 of 7
Quiet
Both cars rest at 1.
Step 1: Quiet
Common mistakes
The bugs interviewers watch for, with the fix beside each.
A call without its direction
criticalThe car opens on the way up for a person who wants down, and erases the call.
Wrongcar.add_stop(call.floor)Rightcar.accept(HallCall(call.floor, call.direction))Moving before waiting
criticalWith the two blocks swapped the car drives while the timer runs.
Wrongself.floor += self.directionif self._open_for: self._open_for -= 1Rightif self._open_for: self._open_for -= 1 return Noneself.floor += self.directionA queue of stops
criticalOrder of arrival is not order of floors.
Wrongself._stops = deque()Rightself._cabin: set[int]self._hall: set[HallCall]Losing the current floor
majorAbove and below are handled, equal is forgotten.
Wrongif floor > self.floor: ...elif floor < self.floor: ...Rightself._cabin.add(floor) # step() opens if it is hereA ghost that shares sets
majorThe estimate erases the real car's stops.
Wrongghost._cabin = self._cabinRightghost._cabin = set(self._cabin)Sleeping in the door
majorA thread waits three seconds and holds what others need.
Wrongif blocked: time.sleep(3)Rightdef tick(self, blocked): ... # called by the loop
Interview tips
Open with
- Two calls: floor with arrow, floor.
- Two decisions: who, where next.
- One tick: open, wait or move.
Reject aloud
- A floor is a number.
- A button is a method call.
- The building is not global.
Prove it
- A down call on the way up.
- Two directions on one floor.
- Random ticks, four rules.
Never
- A priority queue of calls.
- All cars to floor 1 if 1 burns.
- Reset without a person.