Design a parcel locker
medium 80 minModel a wall of doors where couriers leave parcels and customers collect them with a code.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Objects behind the wall: calls travel, states change, and the matching lines light up.
Operations
Deposit
Claim and mark under the lock, then move the metal.
Step 1 of 6
Before sunrise
Five free doors. The courier knows only the locker.
Step 1: Before sunrise
def deposit(self, parcel): with self._lock: door = self._rack.claim(parcel.size) if door is None: return None door.state, door.parcel = DoorState.LOADING, parcel self._hardware.unlock(door.number) return door.number- Cost
- O(1)
- Guarantee
- One door, one parcel
- Scan of 60 doors
- up to 60 looks
No code exists yet. The parcel is still in the baker's hands.
In the real world
The same parcel locker doing real jobs. Pick one and step through it.
The relay does not answer.
Step 1 of 4
Claimed
Door 3 is LOADING, the relay is asked.
Step 1: Claimed
Common mistakes
The bugs interviewers watch for, with the fix beside each.
occupied as a yes or no
criticalOpen for loading, full, and open for emptying look the same, and react to nothing.
Wrongdoor.occupied = TrueRightdoor.state = DoorState.LOADINGFree when the code was typed
criticalThe next courier is sent to an open door with a customer in front of it.
Wrongdel self._stays[code]self._rack.release(door)Rightdel self._stays[code]door.state = DoorState.EMPTYING # released by door_shutThe code before the parcel
criticalThe message is faster than the hand. The customer stands in front of nothing.
Wrongdoor = self._rack.claim(size)self._notifier.send(phone, self._new_code())Right# in door_shut, when the state was LOADINGstay = self._start_stay(door)A timer empties the door
criticalThe flag changes and the parcel does not. And timers die with the process.
WrongTimer(3 * 86400, door.clear).start()Rightif self._now() >= stay.until: raise CodeRefused()random for secrets
majorThe generator can be predicted from its output.
Wrongcode = str(random.randint(1000, 9999))Rightcode = f"{secrets.randbelow(10**8):08d}"Metal under the lock
majorOne stuck relay stops the whole wall.
Wrongwith self._lock: door = self._rack.claim(size) self._hardware.unlock(door.number)Rightwith self._lock: door = self._rack.claim(size)self._hardware.unlock(door.number)
Interview tips
Open with
- One parcel from van to hand.
- Stop the film: what is the door doing?
- Four states.
Ask
- Is there a sensor?
- Who empties it after three days?
- Who makes a field, who ends it?
Prove it
- Shut twice.
- Code twice.
- The last second.
Never
- Free by a timer.
- Two error texts.
- A code in the log.