algoadvance

Leetcode 1603. Design Parking System

Problem Statement

Leetcode Problem 1603 - Design Parking System

You are required to design a parking system for a parking lot. The parking lot has different slots for different sizes of cars:

At the start, the parking lot contains a certain number of slots for each size. You need to provide functionality to add a car of different sizes into the parking lot. If there is still a place in the slot for the car size, it is parked successfully and true is returned. Otherwise, false is returned.

Implement the ParkingSystem class:

Clarifying Questions

  1. Initial Slots: Can the initial number of slots for each type be zero?
  2. Concurrent Access: Can we assume there is no concurrent access (single-threaded execution)?
  3. Valid Input: Can we assume the input is always valid, meaning carType will always be in the set {1, 2, 3}?

Code

#include <iostream>

class ParkingSystem {
private:
    int big;
    int medium;
    int 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;
    }
};

// Example of usage
int main() {
    ParkingSystem* parkingSystem = new ParkingSystem(1, 1, 0);
    std::cout << parkingSystem->addCar(1) << std::endl; // returns true because there is 1 available slot for a big car
    std::cout << parkingSystem->addCar(2) << std::endl; // returns true because there is 1 available slot for a medium car
    std::cout << parkingSystem->addCar(3) << std::endl; // returns false because there is no available slot for a small car
    std::cout << parkingSystem->addCar(1) << std::endl; // returns false because there is no available slot for a big car, it is already occupied
    delete parkingSystem;
    return 0;
}

Strategy

Time Complexity

The solution provided is efficient and meets the problem requirements effectively.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI