Problem 1603

Abstract / Summary

Design a parking system that assigns big medium and small spots based on vehicle type.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1603.py

class ParkingSystem:
    def __init__(self, big: int, medium: int, small: int):
        self.space = [ 0, big, medium, small ]

    def addCar(self, carType: int) -> bool:
        if self.space[carType] == 0:
            return False

        self.space[carType] -= 1
        return True
10 lines | 298 bytes | submitted October 17, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 87% (400k+ submissions).

Typical patterns to solve this problem:
  • Counting
  • Design
  • Simulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided ParkingSystem class models a simple parking lot that tracks three categories of vehicle sizes: big, medium, and small. It stores the remaining capacity for each category and offers an addCar operation that attempts to park a vehicle of a given type, returning a Boolean result that indicates success or failure.

Core Structure

The class consists of an initializer and a single public method.

class ParkingSystem:
    def __init__(self, big: int, medium: int, small: int):
        self.space = [ 0, big, medium, small ]

The initializer receives three integer arguments that represent the total number of parking slots for each vehicle size. These values are placed into a list named space. The list is deliberately indexed from 1, leaving index 0 set to 0 as a sentinel. This layout enables direct indexing by the carType argument used later, eliminating the need for a mapping structure.

Adding a Vehicle

The addCar method embodies the primary logic of the system.

    def addCar(self, carType: int) -> bool:
        if self.space[carType] == 0:
            return False

        self.space[carType] -= 1
        return True

The method proceeds in three distinct steps:

  1. Availability Check - The current count for the requested carType is read from the space list. If the count equals 0, the method returns False immediately, indicating that no slot of the requested size is free.

  2. Slot Reservation - When a slot is available, the count is decremented by 1. This operation updates the internal state to reflect the newly occupied space.

  3. Success Indication - After the decrement, the method returns True, confirming that the vehicle has been successfully parked.

Edge-Case Handling

The design implicitly addresses several edge conditions:

  • Zero Capacity - If any of the initial capacities (big, medium, small) is supplied as 0, the corresponding entry in space starts at 0. The availability check will reject any attempt to park a vehicle of that type, returning False without altering state.

  • Out-of-Range carType - Because index 0 of space is preset to 0, a call with carType equal to 0 behaves like a request for a non-existent category: the availability check fails and False is returned. This prevents accidental modification of the list and provides a graceful failure mode for invalid input.

  • Repeated Parking Until Exhaustion - The decrement operation continues until the count reaches 0. Subsequent calls for the same carType will be rejected, ensuring that the system never reports a successful parking when no slots remain.

Performance Optimizations

The implementation leverages a flat list for storage, granting constant-time access to the slot count via direct indexing. This eliminates the overhead of dictionary lookups or conditional branching based on the vehicle size. The method contains a single conditional test followed by an arithmetic operation, resulting in minimal instruction count per call. By avoiding any loops or auxiliary data structures, the code maintains a tight memory footprint and fast execution path for each parking request.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a parking garage that has special spots for different sizes of vehicles. When this parking garage is first built, it gets a set number of spots for big cars, medium cars, and small cars. Those spots are kept in a little list to help the garage owner remember how many are still empty.

Whenever a car drives up to the entrance, the garage checks which kind of car it is. If the garage sees that there are no empty spots left for that specific size of car, it sends the car away because it cannot fit. If there is at least one spot available, the garage lets the car drive in and park. Once the car is parked, there is one fewer spot left for any other cars that might come along later.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.81 | σ = 1.19

Complexity Analysis

Time: constant
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# Go C Rust TS
Progiez C++ Python Java
github black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune JS
lkwq007 Python
shreymehul C#
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, C#, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune JavaScript
lkwq007 Python
shreymehul C#
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
34 links | 20 authors | 10 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

1 easy 5 medium
7 solutions   October 17, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality