krahets/hello-algo · error · IndexError
雙向佇列為空
Error message
雙向佇列為空
What it means
Raised by peek_first() of a circular-array-based deque when the deque has zero elements. The check uses is_empty() which tests _size == 0. Since pop_first() delegates to peek_first() to retrieve the front value before advancing the _front pointer, both operations fail identically on an empty deque.
Source
Thrown at zh-hant/codes/python/chapter_stack_and_queue/array_deque.py:76
def pop_first(self) -> int:
"""佇列首出列"""
num = self.peek_first()
# 佇列首指標向後移動一位
self._front = self.index(self._front + 1)
self._size -= 1
return num
def pop_last(self) -> int:
"""佇列尾出列"""
num = self.peek_last()
self._size -= 1
return num
def peek_first(self) -> int:
"""訪問佇列首元素"""
if self.is_empty():
raise IndexError("雙向佇列為空")
return self._nums[self._front]
def peek_last(self) -> int:
"""訪問佇列尾元素"""
if self.is_empty():
raise IndexError("雙向佇列為空")
# 計算尾元素索引
last = self.index(self._front + self._size - 1)
return self._nums[last]
def to_array(self) -> list[int]:
"""返回陣列用於列印"""
# 僅轉換有效長度範圍內的串列元素
res = []
for i in range(self._size):
res.append(self._nums[self.index(self._front + i)])
return res
View on GitHub (pinned to 69932aed18)
Solutions
- Check deque.is_empty() before calling peek_first() or pop_first()
- Use while not deque.is_empty() as the loop condition when draining
- Guard with try/except IndexError for defensive front-access
Example fix
# before val = deque.peek_first() # after val = deque.peek_first() if not deque.is_empty() else None
Defensive patterns
Strategy: validation
Validate before calling
if not deque.is_empty():
val = deque.peek_first()
else:
val = None Try / catch
try:
val = deque.peek_first()
except IndexError:
val = None Prevention
- Check is_empty() before peek_first() or pop_first()
- Note that pop_first() internally calls peek_first(), so it inherits the guard
- Use size() as the loop bound in single-ended draining loops
When it happens
Trigger: Calling peek_first() or pop_first() on a freshly constructed ArrayDeque before any push; draining all elements and then accessing the front once more.
Common situations: Sliding-window algorithms that peek at the front after the window empties; BFS implementations where the deque is exhausted; testing edge cases with empty initial data.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/7ab28bc6bc8fed6d.
Report an issue: GitHub.