We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Design Parking System

Number: 1708

Difficulty: Easy

Paid? No

Companies: Amazon, Uber


Problem Description

Design a parking system for a parking lot that has three types of parking spaces: big, medium, and small. The ParkingSystem class is initialized with a fixed number of slots for each type. The addCar method checks if a car of a specified type (1 for big, 2 for medium, 3 for small) can be parked. If there is an available slot for the corresponding type, the car parks (the slot count is decreased) and the method returns true; otherwise, it returns false.


Key Insights

  • Use variables to track the available slots for each parking space type.
  • The solution requires constant-time operations: each addCar call only checks and updates one counter.
  • Memory usage is minimal since only three counters are maintained.

Space and Time Complexity

Time Complexity: O(1) per addCar operation
Space Complexity: O(1)


Solution

We can solve this problem by storing three counters representing the number of available slots for big, medium, and small cars. During initialization, these counters are set to the values provided. For each addCar call, we check the counter corresponding to the car type to see if a slot is available. If yes, we decrement the counter and return true, otherwise return false. This approach uses simple arithmetic and condition checks, leading to constant time per operation.


Code Solutions

# Python implementation of the ParkingSystem class

class ParkingSystem:
    # Constructor initializes the counters for each parking type.
    def __init__(self, big: int, medium: int, small: int):
        # Available slots for big, medium, and small cars.
        self.spaces = {
            1: big,    # big car slots
            2: medium, # medium car slots
            3: small   # small car slots
        }
    
    # Method to add a car to the parking system
    def addCar(self, carType: int) -> bool:
        # Check if there is an available slot for this car type.
        if self.spaces.get(carType, 0) > 0:
            # Decrement slot count as the car parks.
            self.spaces[carType] -= 1
            return True
        else:
            return False

# Example usage:
# parkingSystem = ParkingSystem(1, 1, 0)
# print(parkingSystem.addCar(1))  # Expected True
# print(parkingSystem.addCar(2))  # Expected True
# print(parkingSystem.addCar(3))  # Expected False
# print(parkingSystem.addCar(1))  # Expected False
← Back to All Questions