Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.

Implement the ParkingSystem class:

Input: Operations in this order
"ParkingSystem": [1, 1, 0]
"addCar" : [1]
"addCar" : [2]
"addCar" : [3]
"addCar" : [1]
Output:
Operation 1 "addCar" : true
Operation 2 "addCar" : true
Operation 3 "addCar" : false
Operation 4 "addCar" : false
Explanation:
parkingSystem.addCar(1); // return true because there is 1 available slot for a big car
parkingSystem.addCar(2); // return true because there is 1 available slot for a medium car
parkingSystem.addCar(3); // return false because there is no available slot for a small car
parkingSystem.addCar(1); // return false because there is no available slot for a big car. (available one already occupied)
Constraints:

Contents

In this approach, we will be creating temporary array with size 3 to store the parking slots count for each type of car, i.e. big, medium and small. Then in addCar(int carType) method, we will check whether there are any parking slots available for the carType passed in, if there are slots available then we will decrement the count by 1 and return true, otherwise return false.

public class ParkingSystem { private int[] parkingSlots = new int[3]; public ParkingSystem(int big, int medium, int small) { parkingSlots[0] = big; parkingSlots[1] = medium; parkingSlots[2] = small; } public boolean addCar(int carType) { if(parkingSlots[carType-1] >0) { parkingSlots[carType - 1] -= 1; // reduce count by 1 once the slot occupied return true; } return false; } public static void main(String[] args) { ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0); System.out.println(parkingSystem.addCar(1)); System.out.println(parkingSystem.addCar(2)); System.out.println(parkingSystem.addCar(3)); System.out.println(parkingSystem.addCar(1)); } }
Complexity Analysis:

Time complexity: Above code runs in O(1) time, because there are only 3 types of car parking slots in the problem.
Space complexity: O(1), since we are only creating a temporary array with size 3.

Above implementations source code can be found at GitHub link for Java code