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 <vector>
2
3class ParkingSystem {
4 std::vector<int> slots;
5public:
6 ParkingSystem(int big, int medium, int small) : slots({big, medium, small}) {}
7
8 bool addCar(int carType) {
9 if (slots[carType - 1] > 0) {
10 slots[carType - 1]--;
11 return true;
12 }
13 return false;
14 }
15};
The C++ solution uses a std::vector to store the available slots for each type of vehicle. It decrements the appropriate index when addCar
is called, using a simple conditional check to determine availability.
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
The Java implementation operates using fields to separate state conditions. addCar
employs a switch statement to discern car types and adjust the associated variable accordingly.