{ glenmccallumcan }

LeetCode 1603. Design Parking System

Mar 23, 2022
2 minutes

Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.

My Solution

I declared a global array variable. I used indexes in this array by carType starting at one (big = 1, medium = 2, small=3) with the value at each of these indexes being the number of spots available. To add a car just check if there is a space available - if yes then decrement and return true otherwise return false.

Time: 8.05

var spots = [];
/**
 * @param {number} big
 * @param {number} medium
 * @param {number} small
 */
var ParkingSystem = function(big, medium, small) {
    spots[1] = big;
    spots[2] = medium;
    spots[3] = small;
};

/** 
 * @param {number} carType
 * @return {boolean}
 */
ParkingSystem.prototype.addCar = function(carType) {
    if (spots[carType] - 1 < 0)
        {
            return false;
        }
    spots[carType]--;
    return true;
};

A Nice Solution

This solution is shorter. Personally, I don’t think the addCar function reads as clean as mine since it is subtracting one for the offset on carType in the count array. Also, the decrement operation is hidden in that line. It almost goes unnoticed. The first time I glanced at it beside the greater than symbol my eyes saw an xml comment closing.

Some notes on what I learned.

  1. this.count … where did ‘this’ come from? In this case it is referring to the global object. I haven’t found a good explanation but it seems acceptable to just reference the count variable from the global object without declaring it.
var ParkingSystem = function(big, medium, small) {
    this.count = [big, medium, small];
};

/** 
 * @param {number} carType
 * @return {boolean}
 */
ParkingSystem.prototype.addCar = function(carType) {
  return this.count[carType - 1]-- > 0;
};