Design Parking System

Easy · Arrays & Hashing · Explanation and code example

Array - II

How it works

This is a more concise version of the array approach. Instead of checking before decrementing, we decrement first and then check if the result is non-negative. The logic works because if there were no available slots, the count becomes negative, which we use to indicate failure. This allows the check and update to happen in a single expression.

Steps

  1. Initialization: Store the slot counts for big, medium, and small in an array spaces.
  2. addCar(carType): Decrement spaces[carType - 1] and return true if the new value is greater than or equal to 0, otherwise return false.

Complexity

  • Time complexity:
    • O(1) time for initialization.
    • O(1) time for each addCar() function call.
  • Space complexity: O(1)

Things to watch for

Off-by-One Index Error

Car types are 1-indexed (1 = big, 2 = medium, 3 = small), but arrays are 0-indexed. Forgetting to subtract 1 causes an index out of bounds error.

Decrementing Before Checking Availability

When using the concise approach that decrements first, you must check the value before decrementing (using post-decrement) or check if the result is non-negative. Checking for > 0 after decrementing gives wrong results.

Python code example

class ParkingSystem:

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

    def addCar(self, carType: int) -> bool:
        self.spaces[carType - 1] -= 1
        return self.spaces[carType - 1] >= 0

C++ code example

class ParkingSystem {
    int spaces[3];

public:
    ParkingSystem(int big, int medium, int small) {
        spaces[0] = big, spaces[1] = medium, spaces[2] = small;
    }

    bool addCar(int carType) {
        return spaces[carType - 1]-- > 0;
    }
};
Source and license

Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.

Your recall check is in progress. Write your attempt before revealing the explanation.

Resume recall check

Browse all problem explanations