The Runtime Theory
easyleetcode#low-level-design#object-oriented

Design Parking System

Build a parking lot with fixed per-type capacity that admits cars only while a slot of that vehicle type remains, decrementing counts on entry.

The Runtime Theory Team1 min read
Solve it

solving happens on the judge — come back and mark it done

Sample cases

inaddCar(1) with 1 big slot free

outtrue, 0 big slots left

inaddCar(1) again with 0 big slots

outfalse

inaddCar(2) with 5 medium slots

outtrue, 4 medium slots left

inlot 1/1/0; addCar(3) small

outfalse — small capacity is 0

The machine owns three counters: one per vehicle type — big, medium, small. Construction takes three integers and stores them as the initial capacity. Every addCar call names a type (1, 2, or 3) and the machine must decide admission in constant time: if the counter for that type is above zero, decrement it and return true; otherwise return false and leave everything untouched.

No data structure is needed beyond the three counters — this problem is intentionally minimal, and the point is to notice that. A dict keyed by car type also works and reads cleanly, but three fields are equally fine. The important invariant is that decrement happens only on successful admission, so the counters always reflect free slots, never total slots or parked cars. Capacity never increases; the machine can only lose slots over its lifetime.

The classic wrong move is storing counts per slot and scanning for a free one. That is O(n) and loses the type distinction. The right model is a direct index: type 1 → big, type 2 → medium, type 3 → small, mapped either by if/elif or by a lookup list indexed with type − 1.

Edge cases: capacity of zero for a type — the machine returns false immediately and forever. Repeated calls after exhaustion return false without changing state. Negative capacities never occur per the constructor contract, so no guard is needed. Every operation is O(1) time and O(1) space.

python
class ParkingSystem:
    def __init__(self, big, medium, small):
        self.slots = [0, big, medium, small]   # index by car type 1..3
 
    def addCar(self, carType):
        if self.slots[carType] == 0:
            return False
        self.slots[carType] -= 1
        return True

More practice in this topic

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.