⚡Flashcard Drill➔
NeetCode #134LC-1603EasyArrays & Hashing
← Back to All Problems

#134 · #1603 · Design Parking System(设计停车系统)

📌 Problem Statement & Constraints

Design a parking system with big, medium and small slots. Implement addCar(carType) returning true if a slot of that size is free (and occupying it), or false otherwise. Constraints: 0 <= big, medium, small <= 1000, 1 <= carType <= 3; at most 1000 calls.

💡 Core Algorithmic Approaches

  1. Keep three counters, one per slot size.
  2. Index them directly by carType - 1 or store a length-4 array so carType maps straight to the slot.
  3. On addCar, decrement the counter if positive and return true; otherwise return false.
  4. This is a pure state-machine warm-up; the only care needed is not to decrement when full.

💻 Benchmark Python3 Implementation

class ParkingSystem:
    def __init__(self, big: int, medium: int, small: int):
        self.slots = [0, big, medium, small]   # index by carType directly

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

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(1) per call.
💾 Space Complexity
O(1): four integers.

⚠️ Interview Pitfalls & Follow-ups

  • Decrementing below zero: the > 0 guard is required, and the counter must not go negative.
  • Using carType - 1 with a length-3 list: both work, but mixing the two conventions is a classic source of off-by-one bugs. Pick one.
  • Returning the remaining count instead of a boolean: the API returns a boolean.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

设计停车系统

请你给一个停车场设计一个停车系统。停车场总共有三种不同大小的车位:大、中、小,每种尺寸分别有固定数目的车位。请你实现 ParkingSystem 类: __init__(big, medium, small) 初始化大、中、小三种尺寸的停车位数量。 addCar(carType) 检测是否有停车位可以停车:carType 为 1 表示大车,2 表示中车,3 表示小车。若对应车位有空余则占用一个并返回 true,否则返回 false。约束:0 ≤ big, medium, small ≤ 1000;1 ≤ carType ≤ 3;最多调用 1000 次 addCar。

核心要点

  • 数组存容量(标准解) :用一个长度 3 的数组存三种车位的剩余数量, addCar 时取 carType - 1 作为下标。
  • 为什么用 carType - 1 :carType 是 1/2/3(人类友好),数组下标是 0/1/2,需要做一次偏移。
  • 判定与扣减 :若剩余数量 &gt; 0 则减一返回 True,否则返回 False。
  • 替代方案 · 三个独立变量 :也可用 big/medium/small 三个属性,但用数组配合下标偏移更简洁,扩展性更好。

常见陷阱

  • 忘记 carType - 1 的偏移 :carType = 3 时若直接用作下标会越界(数组长度 3,合法下标 0..2)。
  • 用 if-elif 三分支处理 :虽然正确,但用数组 + 下标偏移更简洁且不易漏分支。
  • 容量为 0 的情况 : big = 0 时大车永远无法停车,本解通过 cap[i] &gt; 0 判断正确覆盖。

参考实现

class ParkingSystem:
    def __init__(self, big: int, medium: int, small: int):
        self.cap = [big, medium, small]      # 下标 0/1/2 对应大/中/小

    def addCar(self, carType: int) -> bool:
        i = carType - 1                      # 1/2/3 -> 0/1/2
        if self.cap[i] > 0:
            self.cap[i] -= 1
            return True
        return False