krahets/hello-algo · error · Error
The Deque Is Empty.
Error message
The Deque Is Empty.
What it means
Thrown by ArrayDeque.peekFirst() ('The Deque Is Empty.') when the deque holds zero elements. peekFirst reads nums[front]; on an empty deque front points at stale/uninitialized storage, so the guard prevents returning garbage. popFirst() delegates to peekFirst(), so it also surfaces here.
Source
Thrown at codes/typescript/chapter_stack_and_queue/array_deque.ts:88
/* 队首出队 */
popFirst(): number {
const num: number = this.peekFirst();
// 队首指针向后移动一位
this.front = this.index(this.front + 1);
this.queSize--;
return num;
}
/* 队尾出队 */
popLast(): number {
const num: number = this.peekLast();
this.queSize--;
return num;
}
/* 访问队首元素 */
peekFirst(): number {
if (this.isEmpty()) throw new Error('The Deque Is Empty.');
return this.nums[this.front];
}
/* 访问队尾元素 */
peekLast(): number {
if (this.isEmpty()) throw new Error('The Deque Is Empty.');
// 计算尾元素索引
const last = this.index(this.front + this.queSize - 1);
return this.nums[last];
}
/* 返回数组用于打印 */
toArray(): number[] {
// 仅转换有效长度范围内的列表元素
const res: number[] = [];
for (let i = 0, j = this.front; i < this.queSize; i++, j++) {
res[i] = this.nums[this.index(j)];
}View on GitHub (pinned to 69932aed18)
Solutions
- Guard with isEmpty(): if (!deque.isEmpty()) deque.peekFirst().
- Loop with while (!deque.isEmpty()).
- Track element count externally and never read the front at zero.
Example fix
// before const head = deque.peekFirst(); // throws when empty // after const head = deque.isEmpty() ? undefined : deque.peekFirst();
Defensive patterns
Strategy: validation
Validate before calling
function safePeekFirst(deque) {
return deque.isEmpty() ? undefined : deque.peekFirst();
} Type guard
null
Try / catch
null
Prevention
- Guard peekFirst/popFirst with isEmpty().
- Use while (!deque.isEmpty()) for draining.
- Do not assume upstream code left elements.
When it happens
Trigger: Calling peekFirst() or popFirst() when queSize === 0; draining the deque in a loop without an emptiness check.
Common situations: Using the deque as a queue/stack and reading the front after it was drained; off-by-one in a consumer loop; calling peek before any push.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/61b2ec9da319fb4b.
Report an issue: GitHub.