Design Parking System

In the ParkingSystem class, we’ll create a parking system with three types of slots: big, medium, and small. We need to implement two functions:

  • __init__: Initialize the number of available slots for each type.
  • addCar: Check if there’s an available slot for the given car type, park the car if there is, and return whether the parking was successful.

We can use a list to maintain the current number of available slots for each car type.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class ParkingSystem:

    def __init__(self, big: int, medium: int, small: int):
        # Initializing the number of slots for each type of car
        self.slots = [0, big, medium, small]

    def addCar(self, carType: int) -> bool:
        # If there is a slot available for the car type
        if self.slots[carType] > 0:
            # Reduce the number of available slots by 1 for the car type
            self.slots[carType] -= 1
            return True
        else:
            return False

# Your ParkingSystem object will be instantiated and called as such:
# obj = ParkingSystem(big, medium, small)
# param_1 = obj.addCar(carType)

Example

  • Initializing the parking system with big = 1, medium = 1, and small = 0.
  • Adding a big car (carType = 1) returns true, since there’s 1 available big slot.
  • Adding a medium car (carType = 2) returns true, since there’s 1 available medium slot.
  • Adding a small car (carType = 3) returns false, since there’s no available small slot.
  • Adding another big car (carType = 1) returns false, since the big slot is already occupied.

Complexity

The time complexity for adding a car is O(1), and the space complexity is also O(1), as we’re using a constant amount of space to store the available slots for each type of car.