algoadvance

You are tasked with designing a ParkingSystem class for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small. The number of each type of parking space is provided during the initialization of the ParkingSystem object. A method addCar is needed to check if there is a parking space available for a car of specified type, and park the car if there’s a spot. The method should return true if the car is successfully parked, and false otherwise.

Here’s the class definition:

class ParkingSystem:

    def __init__(self, big: int, medium: int, small: int):
        pass

    def addCar(self, carType: int) -> bool:
        pass

Clarifying Questions

  1. Can we assume that the given number of parking spaces (big, medium, small) are non-negative integers?
  2. Should we consider thread safety in our implementation?
  3. Is the parking system initialized once and used multiple times for querying, or do we need to reset it during the use case?

Strategy

  1. Initialization:
    • During the initialization, store the number of big, medium, and small parking spaces.
  2. Adding a Car:
    • Based on the carType provided, check if there are available spaces in the respective parking category.
    • If space is available, decrement the space count for that category and return true.
    • If no space is available, return false.

Code

Here’s the complete implementation of the ParkingSystem class:

class ParkingSystem:

    def __init__(self, big: int, medium: int, small: int):
        self.big = big
        self.medium = medium
        self.small = small

    def addCar(self, carType: int) -> bool:
        if carType == 1:
            if self.big > 0:
                self.big -= 1
                return True
            else:
                return False
        elif carType == 2:
            if self.medium > 0:
                self.medium -= 1
                return True
            else:
                return False
        elif carType == 3:
            if self.small > 0:
                self.small -= 1
                return True
            else:
                return False
        else:
            return False  # Invalid car type

Time Complexity

This solution ensures that adding a car to the parking system is efficient and quick, with a guaranteed O(1) time complexity per operation.

Try our interview co-pilot at AlgoAdvance.com