krahets/hello-algo · error · IndexError
Queue is empty
Error message
Queue is empty
What it means
Raised by LinkedListQueue#peek (en/codes/ruby/chapter_stack_and_queue/linkedlist_queue.rb:55) when the queue is empty. peek dereferences @front.val; the guard rejects it because @front is nil when size == 0. pop calls peek first, so dequeue on an empty queue surfaces the same message.
Source
Thrown at en/codes/ruby/chapter_stack_and_queue/linkedlist_queue.rb:55
@rear.next = node
@rear = node
end
@size += 1
end
### Dequeue ###
def pop
num = peek
# Delete head node
@front = @front.next
@size -= 1
num
end
### Access front element ###
def peek
raise IndexError, 'Queue is empty' if is_empty?
@front.val
end
### Convert linked list to Array and return ###
def to_array
queue = []
temp = @front
while temp
queue << temp.val
temp = temp.next
end
queue
end
end
### Driver Code ###
if __FILE__ == $0View on GitHub (pinned to 69932aed18)
Solutions
- Check queue.is_empty? before peek or pop.
- Track enqueued/dequeued counts and never dequeue more than enqueued.
- Rescue IndexError around dequeue and treat empty as a normal idle state.
Example fix
# before queue = LinkedListQueue.new queue.pop # raises IndexError, "Queue is empty" # after queue.pop unless queue.is_empty?
Defensive patterns
Strategy: validation
Validate before calling
queue.pop unless queue.is_empty?
Type guard
def queue_nonempty?(q); q.respond_to?(:is_empty?) && !q.is_empty?; end
Try / catch
begin queue.pop rescue IndexError nil end
Prevention
- Check is_empty? before peek/pop.
- Never dequeue more times than you enqueued.
- Use emptiness as the idle/exit signal in consumer loops.
When it happens
Trigger: Calling queue.peek or queue.pop when queue.size == 0 — before the first enqueue, or after the head has advanced past every node via successive pops.
Common situations: A BFS work-queue drained to empty then peeked again; a producer/consumer loop where the consumer outruns the producer; test code that pops more than it enqueues.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/f0b94675b404b811.
Report an issue: GitHub.