krahets/hello-algo · error · IndexError
Queue is empty
Error message
Queue is empty
What it means
Raised by ArrayQueue#peek (en/codes/ruby/chapter_stack_and_queue/array_queue.rb:52) when the queue holds zero elements. ArrayQueue is a hand-written circular-array queue from the hello-algo teaching code; peek guards the front-access precondition because reading @nums[@front] is undefined when size == 0. Because pop calls peek first (line 43), any dequeue on an empty queue surfaces the same message.
Source
Thrown at en/codes/ruby/chapter_stack_and_queue/array_queue.rb:52
# Add num to the rear of the queue
rear = (@front + size) % capacity
# Front pointer moves one position backward
@nums[rear] = num
@size += 1
end
### Dequeue ###
def pop
num = peek
# Move front pointer backward by one position, if it passes the tail, return to array head
@front = (@front + 1) % capacity
@size -= 1
num
end
### Access front element ###
def peek
raise IndexError, 'Queue is empty' if is_empty?
@nums[@front]
end
### Return list for printing ###
def to_array
res = Array.new(size, 0)
j = @front
for i in 0...size
res[i] = @nums[j % capacity]
j += 1
end
res
end
end
View on GitHub (pinned to 69932aed18)
Solutions
- Guard the call: only peek/pop when queue.is_empty? returns false (or queue.size > 0).
- Track the count of successful pushes and never pop more times than you have pushed.
- Wrap the dequeue in a rescue IndexError block to supply a sentinel/nil when the queue legitimately runs dry.
Example fix
# before queue = ArrayQueue.new(10) queue.pop # raises IndexError, "Queue is empty" # after queue.pop unless queue.is_empty?
Defensive patterns
Strategy: validation
Validate before calling
queue.pop if queue.size > 0 && !queue.is_empty?
Type guard
# ArrayQueue exposes size and is_empty?; no type guard needed. def dequeable?(q); q.respond_to?(:is_empty?) && !q.is_empty?; end
Try / catch
begin queue.pop rescue IndexError => e nil # queue legitimately empty end
Prevention
- Always call is_empty? (or check size > 0) before peek or pop.
- Track the number of pushes and never pop more times than you pushed.
- In producer/consumer loops, make emptiness the loop's exit condition.
When it happens
Trigger: Calling queue.peek or queue.pop when queue.size == 0. Happens on a freshly constructed ArrayQueue.new(10) before any push, or after draining every pushed element via successive pop calls (e.g. the driver's enqueue+dequeue loop overshooting count).
Common situations: Draining a queue in a producer/consumer loop without an emptiness check; running the driver's circular-array test loop one iteration too many; reusing a queue instance across test cases assuming it was repopulated.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/6bdab46f5d82eeab.
Report an issue: GitHub.