Leetcode 1603. Design Parking System
You are asked to design a parking system for a parking lot. The parking system has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.
Implement the ParkingSystem
class:
ParkingSystem(int big, int medium, int small)
Initializes the object of the ParkingSystem
class. The number of slots for each parking space are given as parameters.boolean addCar(int carType)
Checks whether there is a parking space of carType
for the car that wants to get into the parking lot. carType
can be one of three values: 1 (big car), 2 (medium car), or 3 (small car). A car can only park in a parking space of its carType
. If there is no space available, return false
, otherwise park the car and return true
.0 <= big, medium, small <= 1000
carType
is an integer with values 1, 2, or 3.We will store the remaining number of slots for each car type using an array or instance variables. When a car arrives with a specific carType
, we will check if there is a slot available in the corresponding category:
true
.false
if no slot is available for that car type.class ParkingSystem {
private int[] slots;
public ParkingSystem(int big, int medium, int small) {
slots = new int[4]; // There are three types, use index 1, 2, 3
slots[1] = big;
slots[2] = medium;
slots[3] = small;
}
public boolean addCar(int carType) {
if (slots[carType] > 0) {
slots[carType]--;
return true;
} else {
return false;
}
}
}
// Example Usage
// ParkingSystem obj = new ParkingSystem(big, medium, small);
// boolean param_1 = obj.addCar(carType);
O(1)
since we’re just storing three integer values.addCar
: O(1)
since checking the availability and updating the slot count is done in constant time.This design ensures the solution is efficient while being simple and straightforward to implement.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?