Sponsored
Sponsored
This approach leverages an array to manage the count of available parking slots for each type of car. The array indices correspond to the car types: index 0 for big cars, index 1 for medium, and index 2 for small. The addCar function decrements the corresponding index if space is available.
Time Complexity: O(1) for each addCar operation as we are directly accessing an array element.
Space Complexity: O(1) as only a fixed-size array is used.
1#include <stdbool.h>
2
3typedef struct {
4 int slots[3];
5} ParkingSystem;
6
7ParkingSystem* parkingSystemCreate(int big, int medium, int small) {
8 ParkingSystem* obj = (ParkingSystem*) malloc(sizeof(ParkingSystem));
9 obj->slots[0] = big;
10 obj->slots[1] = medium;
11 obj->slots[2] = small;
12 return obj;
13}
14
15bool parkingSystemAddCar(ParkingSystem* obj, int carType) {
16 if (obj->slots[carType - 1] > 0) {
17 obj->slots[carType - 1]--;
18 return true;
19 } else {
20 return false;
21 }
22}
23
24void parkingSystemFree(ParkingSystem* obj) {
25 free(obj);
26}
The code uses a struct with an array of size 3 to store slots available for each car type. carType is 1-indexed due to the problem constraints but is used as 0-indexed for array access. The parkingSystemAddCar
function decrements the respective slot count if the slot is available. Memory is dynamically allocated and should be freed when done.
This method uses distinct variables to handle each type of car's parking slots. This approach makes the code very clear for small data sets. While this isn't necessarily more efficient than the array method for this particular problem, it offers an alternative for simple systems where explicit clarity is beneficial.
Time Complexity: O(1) for checking and updating.
Space Complexity: O(1) as three variables track the state.
1 int big, medium, small;
public:
ParkingSystem(int big, int medium, int small) : big(big), medium(medium), small(small) {}
bool addCar(int carType) {
if (carType == 1) {
if (big > 0) { big--; return true; }
} else if (carType == 2) {
if (medium > 0) { medium--; return true; }
} else if (carType == 3) {
if (small > 0) { small--; return true; }
}
return false;
}
};
This code uses dedicated variables for each parking slot type. The addCar
function updates the correct variable similar to the array-based solution but directly checks carType through conditionals.