Problem
A parking lot has a fixed number of big, medium and small slots. addCar(carType) parks a car of that type, where 1 is big, 2 is medium and 3 is small, and returns whether a slot was available. A car can only use a slot of its own size.
Original: LeetCode 1603: Design Parking System.
Examples
Example 1
`ParkingSystem: ParkingSystem(1, 1, 0), addCar(1), addCar(2), addCar(3), addCar(1)``[null, true, true, false, false]`There is no small slot, and the one big slot is already taken by the last call.
Constraints
0 <= big, medium, small <= 1000carTypeis1,2, or3- At most
1000calls will be made toaddCar
Hints
Hint 1
The constructor receives the three capacities. There is no unpark method in this problem, so counters only go down.
Hint 2
This is simple state management: three integers, or a small array indexed by type.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. You could store every parked car, but the only thing you need is the remaining count.
Optimal. An int[4] of remaining slots, ignoring index 0.
Alternative. Three named fields are just as clear.
Complexity
- Time
- O(1)
Each operation is O(1) time and the object uses O(1) space.
- Space
- O(1)
Code
class ParkingSystem:
def __init__(self, big: int, medium: int, small: int) -> None:
self.slots = {1: big, 2: medium, 3: small}
def add_car(self, car_type: int) -> bool:
if self.slots[car_type] == 0:
return False
self.slots[car_type] -= 1
return True
if __name__ == "__main__":
p = ParkingSystem(1, 1, 0)
assert p.add_car(1) is True
assert p.add_car(2) is True
assert p.add_car(3) is False
assert p.add_car(1) is False
print("ok")public class DesignParkingSystem {
private final int[] slots;
DesignParkingSystem(int big, int medium, int small) {
slots = new int[] {0, big, medium, small};
}
boolean addCar(int carType) {
if (slots[carType] == 0) return false;
slots[carType]--;
return true;
}
public static void main(String[] args) {
var p = new DesignParkingSystem(1, 1, 0);
if (!p.addCar(1)) throw new AssertionError();
if (!p.addCar(2)) throw new AssertionError();
if (p.addCar(3)) throw new AssertionError();
if (p.addCar(1)) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official sample: ParkingSystem(1, 1, 0), then addCar(1) and addCar(2) succeed, addCar(3) fails because there is no small slot, and a second addCar(1) fails because the one big slot is taken.
Follow-ups
- If a bigger car could use a smaller unused slot, or if unpark were added, you would need a more general allocation policy.
Interview script
"I just keep the remaining count for each size. addCar returns false when that count is already zero, otherwise it decrements and returns true."
Sources (1)
- LeetCode 1603: Design Parking Systemleetcode.com