Design Parking System
Problem
Design a parking system for a lot with three slot sizes: big, medium, and small, with a fixed number of each.
Implement ParkingSystem(int big, int medium, int small) and boolean addCar(int carType) where carType is 1 (big), 2 (medium), or 3 (small). Return true if a slot of that size is free (and occupy it), else false.
Constraints
- 0 ≤ big, medium, small ≤ 1000
- carType ∈ {1, 2, 3}
- at most 1000 addCar calls
Approach — Hashing & Counting
This is a Hashing & Counting problem. The idea: store what you've seen in a hash map for O(1) lookups, trading a little space to avoid a nested scan. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time, O(n) space.
Solution code
Python
class ParkingSystem:
def __init__(self, big, medium, small):
self.slots = {1: big, 2: medium, 3: small}
def addCar(self, carType):
if self.slots[carType] > 0:
self.slots[carType] -= 1
return True
return False
Java
class ParkingSystem {
private int[] slots;
public ParkingSystem(int big, int medium, int small) {
// index 0 unused so carType maps directly to an index
slots = new int[]{0, big, medium, small};
}
public boolean addCar(int carType) {
if (slots[carType] > 0) {
slots[carType]--;
return true;
}
return false;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Design Parking System interactively → ← All solutions