krahets/hello-algo · error · IndexError

佇列已滿

Error message

佇列已滿

What it means

Raised by the push() method of a circular-array-based queue when the number of elements equals the allocated capacity. Unlike ArrayDeque (which silently prints and returns on overflow), ArrayQueue raises an IndexError to enforce a hard capacity limit. The capacity is fixed at construction time (len(self._nums)) and does not auto-expand.

Source

Thrown at zh-hant/codes/python/chapter_stack_and_queue/array_queue.py:32

        self._front: int = 0  # 佇列首指標,指向佇列首元素
        self._size: int = 0  # 佇列長度

    def capacity(self) -> int:
        """獲取佇列的容量"""
        return len(self._nums)

    def size(self) -> int:
        """獲取佇列的長度"""
        return self._size

    def is_empty(self) -> bool:
        """判斷佇列是否為空"""
        return self._size == 0

    def push(self, num: int):
        """入列"""
        if self._size == self.capacity():
            raise IndexError("佇列已滿")
        # 計算佇列尾指標,指向佇列尾索引 + 1
        # 透過取餘操作實現 rear 越過陣列尾部後回到頭部
        rear: int = (self._front + self._size) % self.capacity()
        # 將 num 新增至佇列尾
        self._nums[rear] = num
        self._size += 1

    def pop(self) -> int:
        """出列"""
        num: int = self.peek()
        # 佇列首指標向後移動一位,若越過尾部,則返回到陣列頭部
        self._front = (self._front + 1) % self.capacity()
        self._size -= 1
        return num

    def peek(self) -> int:
        """訪問佇列首元素"""
        if self.is_empty():

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check queue.size() < queue.capacity() before calling push()
  2. Increase the capacity argument at construction time to match peak load
  3. Pop before pushing if you need a fixed-size circular buffer that drops old items
  4. Switch to collections.deque if unbounded growth is acceptable

Example fix

# before
queue = ArrayQueue(5)
for i in range(10):
    queue.push(i)  # crashes at i=5

# after
queue = ArrayQueue(10)
for i in range(10):
    queue.push(i)
# or check before push:
if queue.size() < queue.capacity():
    queue.push(i)
Defensive patterns

Strategy: validation

Validate before calling

if queue.size() < queue.capacity():
    queue.push(num)
else:
    # either increase capacity or drop oldest item
    queue.pop()
    queue.push(num)

Try / catch

try:
    queue.push(num)
except IndexError:
    print("queue full, dropping item")

Prevention

When it happens

Trigger: Pushing more items than the constructor-specified capacity without popping in between; enqueuing at a rate faster than dequeuing in a producer-consumer setup; using a small capacity (e.g., ArrayQueue(5)) and overfilling it.

Common situations: Burst traffic exceeding a fixed buffer size; choosing an undersized capacity for the workload; forgetting that this queue does not auto-grow unlike Python's collections.deque.

Related errors


AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13). Data as JSON: /api/errors/dd76038769f29079. Report an issue: GitHub.