krahets/hello-algo · error · IndexError

Deque is empty

Error message

Deque is empty

What it means

Raised by `ArrayDeque#peek_first` (array_deque.rb:76, English version) when `is_empty?` is true. Reads `@nums[@front]`; on an empty deque `@front` is stale and the slot is uninitialized, so the guard prevents returning garbage. Note: the overflow path (`push_first`/`push_last` when full) only prints and returns — overflow is silent, but empty access raises.

Source

Thrown at en/codes/ruby/chapter_stack_and_queue/array_deque.rb:76

  ### Dequeue from front ###
  def pop_first
    num = peek_first
    # Move front pointer backward by one position
    @front = index(@front + 1)
    @size -= 1
    num
  end

  ### Dequeue from rear ###
  def pop_last
    num = peek_last
    @size -= 1
    num
  end

  ### Access front element ###
  def peek_first
    raise IndexError, 'Deque is empty' if is_empty?

    @nums[@front]
  end

  ### Access rear element ###
  def peek_last
    raise IndexError, 'Deque is empty' if is_empty?

    # Initialize double-ended queue
    last = index(@front + size - 1)
    @nums[last]
  end

  ### Return array for printing ###
  def to_array
    # Elements enqueue
    res = []
    for i in 0...size

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check `deque.is_empty?` before `peek_first` or `pop_first`.
  2. Return nil explicitly when empty.
  3. Rescue IndexError if empty front-access is expected control flow.

Example fix

# before
front = deque.peek_first

# after
front = deque.is_empty? ? nil : deque.peek_first
Defensive patterns

Strategy: validation

Validate before calling

return nil if deque.is_empty?
deque.peek_first

Type guard

def deque_readable?(deque)
  deque.respond_to?(:is_empty?) && deque.respond_to?(:peek_first) && !deque.is_empty?
end

Try / catch

begin
  deque.peek_first
rescue IndexError
  nil
end

Prevention

When it happens

Trigger: Calling `deque.peek_first` or `deque.pop_first` (delegates via `peek_first`) on an empty deque. Occurs after draining all elements or before the first push.

Common situations: Deque as a sliding window fully consumed between frames; peek before first enqueue; consumer loop over-pops.

Related errors


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