Skip to content

1603. Design Parking System

On LeetCode ->

Problem

Create a parking system with fixed numbers of big, medium, and small spaces. addCar(carType) parks a car in a matching space and returns whether it succeeded.

ParkingSystem(1, 1, 0)
addCar(1) → True
addCar(2) → True
addCar(3) → False
addCar(1) → False
class ParkingSystem:
    def __init__(self, big: int, medium: int, small: int):
       pass

     def addCar(self, carType: int) -> bool:
         pass

Key trick

Store the three remaining capacities in a list; carType - 1 selects the matching space.

Trap

Do not decrement a capacity when it is already zero, or allow one car type to use another type's space.

Why is it interesting?

It tests whether you can model persistent state with a minimal, constant-time operation.

Python solution

class ParkingSystem:
    def __init__(self, big: int, medium: int, small: int):
        self.remaining = [big, medium, small]

    def addCar(self, carType: int) -> bool:
        idx = carType - 1
        if self.remaining[idx] == 0:
            return False
        self.remaining[idx] -= 1
        return True

Time: \(O(1)\) per call. Space: \(O(1)\).

Comment on my solution

Your solution is correct. The else is unnecessary after a return, and storing the index once avoids repeating carType - 1.

class ParkingSystem:

    def __init__(self, big: int, medium: int, small: int):
        self.capacity = [big, medium, small]


    def addCar(self, carType: int) -> bool:
        if self.capacity[carType - 1] > 0:
            self.capacity[carType - 1] -= 1
            return True
        else:
            return False