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
|
|
Example
- Initializing the parking system with
big = 1
,medium = 1
, andsmall = 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.