Skip to content

What is a Queue?

Data Structures·6 min·Python code

Queues store items in first in, first out (FIFO) order, so the earliest arrival leaves first. Enqueue adds at the back, dequeue removes from the front, and both cost O(1) time with the right backing.

How a Queue Keeps Arrival Order

Picture a checkout line. Whoever arrives first is served first, and new people join at the back.

That rule translates straight into code. First in, first out is the defining trait, and it is the opposite of a stack, which serves the latest arrival first.

Order stays intact, so FIFO suits any job where fairness or arrival order matters, like handling requests as they came in, replaying events or visiting things layer by layer. Two ends do the work, since you always add at the back and remove from the front.

Core Operations and Implementation Choices

Four core operations drive the structure. Enqueue adds to the back, dequeue removes and returns the front, peek shows the front without removing it and isEmpty checks for items. Done right, every one costs O(1).

Your implementation decides whether O(1) holds. Linked lists with head and tail pointers work, and so do deques and circular buffers.

Dynamic arrays are the common trap. Dequeue on index 0 shifts every remaining element down, and that quietly turns an O(1) operation into O(n).

Breadth-First Search leans on a queue for this reason. BFS keeps the frontier of nodes to visit, and dequeuing in FIFO order reaches nodes in increasing distance from the source, which finds shortest paths in unweighted graphs.

Circular Queues and Deques Explained

Circular queues are fixed size arrays whose front and rear indices wrap around with the modulo operator. They reuse slots freed by earlier dequeues instead of shifting elements or growing without bound.

That suits bounded buffers, like ring buffers for streaming audio, keyboard input or producer and consumer pipelines with capped memory.

Deques, short for double ended queues, allow O(1) insertion and removal at both ends. They act as a stack or a queue and power patterns like sliding window maximum. Python's collections.deque and Java's ArrayDeque are the practical way to build one.

Practise queues on CodeStory's queue practice problems.

Queue Code Example in Python

pythonFIFO queue backed by collections.deque in Python with O(1) enqueue and dequeue.

from collections import deque

class Queue:
    def __init__(self):
        self._items = deque()

    def enqueue(self, item):        # add to the back
        self._items.append(item)

    def dequeue(self):              # remove from the front
        if not self._items:
            raise IndexError("dequeue from empty queue")
        return self._items.popleft()

    def peek(self):                 # front without removing
        if not self._items:
            raise IndexError("peek from empty queue")
        return self._items[0]

    def is_empty(self):
        return len(self._items) == 0

Edit this code in the browser IDE on CodeStory, free on the platform. Open the CodeStory App

Queue Time and Space Complexity

TimeO(1) for enqueue, dequeue, peek and isEmpty
SpaceO(n) for n stored elements

Deques, linked lists and circular arrays keep every operation at O(1) in every case. Classic trap is a dynamic array that removes from the front, like Python's list.pop(0). It costs O(n) because every remaining element shifts down one slot, so a sequence of dequeues becomes quadratic.

When to Use a Queue

  • Breadth first search and level order traversal of trees or graphs, where nodes are visited in order of distance from the start.
  • Scheduling and task processing in arrival order, like job queues, print spoolers, message queues and round robin work.
  • Buffering data between a quick producer and a slow consumer, typically with a fixed size circular buffer.
  • Shortest number of steps problems on an unweighted grid or graph, where FIFO order yields the minimum step answer.

Mistakes to Avoid

  • Using list.pop(0) in Python, or otherwise shifting an array, to dequeue. It costs O(n) per removal and makes a loop of dequeues quadratic, so use collections.deque or a linked list.
  • Dequeuing or peeking without checking whether anything is queued, which raises an error or returns undefined and crashes the surrounding logic.
  • Mishandling the full versus empty case in a fixed size circular queue. When front and rear point to the same slot, you need a count or a spare slot to tell empty from full.

Queue FAQs

What is the time complexity of a queue?

Enqueue, dequeue and peek cost O(1) when a linked list, deque or circular array backs it. Space is O(n) for n elements. Removing from the front of a plain dynamic array is the one way to slip to O(n), because every remaining element shifts.

What is the difference between a stack and a queue?

Queues serve the earliest arrival first, like people in a line. Stacks serve the latest arrival first, like plates in a pile. Queues drive breadth-first search, and stacks drive depth-first search and recursion.

Why shouldn't I use a Python list as a queue?

list.append costs O(1), but list.pop(0) costs O(n) because Python shifts every remaining element one position left. Many dequeues make dequeue quadratic. Use collections.deque, where popleft costs O(1).

Is a queue hard to learn?

No. FIFO mirrors an everyday line. Subtle parts are choosing an implementation that keeps dequeue at O(1) and getting circular queue wrap around right. Tracing enqueue and dequeue on paper makes both click.

What is a circular queue?

Fixed size arrays with front and rear indices that wrap around using modulo make a circular queue. They reuse freed slots, so memory stays capped and no elements shift.

What is a deque?

Deques are double ended queues with O(1) insertion and removal at both ends. They work as a stack or a queue, and Python's collections.deque is the standard way to build one.

How do I practise queues on CodeStory?

Work through CodeStory's queue practice problems, and trace every enqueue and dequeue before you code it.

Related Guides

Guides are step one. In a CodeStory batch you build the queue yourself, then explain every enqueue and dequeue in a scored mock round.

Talk to a Mentor

Stuck on FIFO? Get a Free Callback

Tell CodeStory which enqueue or dequeue step confuses you, and a mentor shapes your next steps.

  1. 1CodeStory finds your starting point, from your first enqueue to interview ready.
  2. 2CodeStory explains online and campus batches, with timings for your mornings or evenings.
  3. 3You decide. No pressure, no payment on the call.

Get a Free Callback

I am a
I want to learn

CodeStory dials your number only for this callback.