liveBook · Manning

Dequeue

As explained in Grokking Data Structures

Dequeue is a queue operation that removes and returns the least recently added element from the front of the queue.

Think of a line at a checkout counter: the person at the front is served first. A queue works the same way. `enqueue()` adds an element at the rear; `dequeue()` removes and returns the element at the front—the one that has waited longest. This is first-in, first-out (FIFO) order. section 9.18 section 9.3

A small queue

Enqueue 4, then 7, then 9. The first `dequeue()` returns 4; the next returns 7. New arrivals join at the rear rather than jumping ahead. section 9.3

In a circular-array queue, `front` identifies the next element to remove. Dequeuing an empty queue raises an error. Otherwise, save the front value, advance `front` by one position—wrapping to the start if needed—decrease the size, and return the saved value. Tracking size also distinguishes an empty array from a full one when `front` and `rear` share an index. section 9.12 section 9.10

def dequeue(self):
    if self.is_empty():
        raise ValueError("Cannot dequeue from an empty queue")
    value = self._data[self._front]
    self._front = (self._front + 1) % self._max_size
    self._size -= 1
    return value

The Python method puts those steps together; the modulo expression handles wraparound without separate end-of-array cases. section 9.12

A linked-list queue can instead remove from the list’s front, with worst-case O(1) dequeue time. A fixed-size circular array reuses cells freed by dequeue, but its capacity remains limited; resizing a dynamic array requires realigning the queued elements. section 9.18 section 9.13

How Grokking Data Structures covers it

How deep it goes
Works through empty checks, front-index updates, modulo wraparound, and size bookkeeping in a Python circular-array implementation.
Examples
Uses a checkout line, numbered queue elements, and a Python dequeue method to show removal order and wraparound.
What it assumes
Introduces queue operations through a familiar line before explaining front and rear indexes; assumes no prior queue knowledge.
What you can do after
Build it from scratch as a Python circular-array operation that rejects empty queues and advances the front correctly.
How it connects
Connects dequeue to enqueue, FIFO queues, circular arrays, linked lists, and stacks.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Data Structures. The section links point to the parts of the book it draws on.