AlgoViz

Design a parking lot

medium 90 min

Model a car park with several levels as classes: vehicles, spaces of different sizes, tickets and a replaceable price rule.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:48

See it run

Objects at the gates: calls travel, fields change, and the matching lines light up.

Operations

A car enters

One call from the gate, four steps under one lock.

Step 1 of 6

At the barrier

ownsgatecallerlotParkingLotactivenoneinsidenonelockfreepoolSpotPoolSMALLS1MEDIUMM1 M2 M3LARGEL1

The lot has five free spaces. The gate knows only the lot.

Step 1: At the barrier

def enter(self, vehicle):    with self._lock:        if vehicle.plate in self._inside:            raise AlreadyInside(vehicle.plate)        spot = self._pool.claim(vehicle.type.min_size)        if spot is None:            return None        ticket = Ticket(next(self._ids), vehicle, spot, self._now())        self._inside.add(vehicle.plate)        self._active[ticket.id] = ticket        return ticket
Cost
O(1)
Guarantee
One space, one ticket
Scan of 500
up to 500 looks

Nothing slow happens while the lock is held.

In the real world

The same parking lot doing real jobs. Pick one and step through it.

What is taken out must be put back.

Step 1 of 4

The ticket is out

gatecallerlotParkingLotactivenoneinsideRED-1lockfreepoolSpotPoolSMALLnoneMEDIUMM3LARGEnonepricingHourlyPricingMEDIUM200paymentsCardMachineticket-1noneticket 1TicketspotM1entered09:00leave(1)

The exit has popped ticket 1. For a moment it is in no list.

Step 1: The ticket is out

def leave(self, ticket_id):    with self._lock:        ticket = self._active.pop(ticket_id, None)    if ticket is None:        raise UnknownTicket(ticket_id)    try:        left_at = self._now()        cents = self._pricing.price_cents(ticket, left_at)        self._payments.charge(f"ticket-{ticket_id}", cents)    except Exception:        with self._lock:            self._active[ticket_id] = ticket        raise    with self._lock:        self._pool.release(ticket.spot)        self._inside.discard(ticket.vehicle.plate)    return Receipt(ticket, left_at, cents)

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Check, then act

    critical

    Two gates pass the check before either acts. One space is sold twice.

    Wrong
    if spot.is_free():    spot.park(car)
    Right
    spot = pool.claim(car.type.min_size)   # finds and takesif spot is None:    show("FULL")
  • Releasing before the charge

    critical

    The card is declined, the car stays, and the space has been given to the next driver.

    Wrong
    pool.release(ticket.spot)payments.charge(key, cents)
    Right
    payments.charge(key, cents)pool.release(ticket.spot)
  • Charging under the lock

    critical

    One slow card stops every entry and every exit.

    Wrong
    with self._lock:    ticket = self._active.pop(ticket_id)    self._payments.charge(key, cents)
    Right
    with self._lock:    ticket = self._active.pop(ticket_id)self._payments.charge(key, cents)      # outside
  • Rounding down

    major

    119 minutes become 1 hour. Nobody complains, so nobody finds it.

    Wrong
    hours = seconds // 3600
    Right
    hours = max(1, (seconds + 3599) // 3600)
  • A subclass for each size

    major

    The next property doubles the tree.

    Wrong
    class LargeElectricSpot(LargeSpot): ...
    Right
    Spot("E1", 1, SpotSize.LARGE, features={"charger"})
  • Asking the system clock

    minor

    A test cannot reach 23:59, or the night when clocks change.

    Wrong
    left_at = datetime.now()
    Right
    left_at = self._now()     # passed in

Interview tips

  • Open with

    • Two verbs: enter, leave.
    • One owner of free spaces.
    • One rule for prices.
  • Reject aloud

    • A level is a number.
    • A gate is a caller.
    • A car is an enum value.
  • Prove it

    • Trace a full lot.
    • Trace a declined card.
    • free + active = total.
  • Never

    • A lock around a card.
    • A float for money.
    • isFull before enter.