</>

1603. Design Parking System

Easy
Arrays & Hashing Time O(1) Space O(1)
↗ Open on LeetCode Source: Misc

Quick review

Pattern
Arrays & Hashing
Time
O(1)
Space
O(1)

Standard Solution (C++)

SummaryDesign a parking lot system that tracks available spots for three car sizes (big, medium, small) and answers whether a car of a given type can be parked, decrementing the count if space is available.

Approach
  • Store the remaining capacity for each car type in a small fixed-size array indexed by type (1-based → 0-based).
  • addCar checks if the corresponding slot count is positive; if so, decrements and returns true, otherwise returns false.
  • All operations are O(1) time and O(1) space because the state is bounded by three integer counters regardless of input size.
#include <array>
using namespace std;

class ParkingSystem {
    // spots[0]=big, spots[1]=medium, spots[2]=small
    array<int, 3> spots;

public:
    ParkingSystem(int big, int medium, int small)
        : spots{big, medium, small} {}

    // carType is 1-based: 1=big, 2=medium, 3=small
    bool addCar(int carType) {
        int& count = spots[carType - 1];
        if (count > 0) {
            --count;
            return true;
        }
        return false;
    }
};
Time O(1) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class ParkingSystem {
private:
    int parkingSpace[3];
public:
    ParkingSystem(int big, int medium, int small) {
        parkingSpace[0]=big;
        parkingSpace[1]=medium;
        parkingSpace[2]=small;
    }
    
    bool addCar(int carType) {
        if(parkingSpace[carType-1]>0){
            --parkingSpace[carType-1];
            return true;
        }

        return false;
    }
};

/**
 * Your ParkingSystem object will be instantiated and called as such:
 * ParkingSystem* obj = new ParkingSystem(big, medium, small);
 * bool param_1 = obj->addCar(carType);
 */

 // Time Complexity: O(1)
 // Space Complexity: O(1)
Time O(1) Space O(1)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground C++

Your solution. A driver couldn't be auto-generated for this signature — add a main() that calls the method and prints the result, then Run.

C++ ▶ Runnable Couldn't auto-generate a driver for this signature — edit to add one.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern