AlgoViz

Queue

easy 15 min

A queue is a linear data structure where items join at the rear and leave from the front.

See it run

Enqueue at the rear, dequeue from the front, then watch the same first-in, first-out line run checkouts, printers, schedulers and BFS.

Operations

Enqueue

Add an element at the rear (back) of the queue. The new element becomes the new REAR.

Step 1 of 4

The queue before

  1. A0FRONT
  2. B1
  3. C2REAR
size = 3

The queue holds [A, B, C]. FRONT is A, the oldest element, and REAR is C, the newest. We want to run enqueue('D').

Step 1: The queue before

def enqueue(self, item):    self.items.append(item)   # join at the rear, O(1)
Time
O(1)
Space
O(1)
vs linked list
O(1) with a tail pointer
vs fixed array
O(1), until it is full

Enqueue is always O(1): it only writes at the rear. Think of joining the back of a line.

In the real world

The same queue doing real jobs. Pick one and step through it.

Customers join the back of the checkout line and the cashier serves whoever is at the front.

Step 1 of 9

Welcome to the checkout

  1. empty
size = 0served = 0arrived = 0

A supermarket checkout line is a perfect FIFO queue. Customers join at the REAR, the back of the line, and the cashier serves from the FRONT. Whoever arrives first is served first, which is what makes it fair.

Step 1: Welcome to the checkout

from collections import dequeline = deque()line.append("C1")        # enqueue: C1 joinsline.append("C2")line.append("C3")served = line.popleft()  # dequeue: serve C1nxt = line[0]            # peek: C2 is nextline.append("C4")served = line.popleft()  # dequeue: serve C2

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Using list.pop(0) as dequeue

    critical

    A Python list is a contiguous array. pop(0) shifts every remaining element left, so each dequeue is O(n) and draining n items is O(n²). It quietly turns a linear BFS quadratic.

    Wrong
    queue = [1, 2, 3]queue.append(4)first = queue.pop(0)     # O(n) shift every time
    Right
    from collections import dequequeue = deque([1, 2, 3])queue.append(4)first = queue.popleft()  # O(1)
  • Dequeuing without checking for empty

    critical

    Dequeue or peek on an empty queue is underflow: IndexError in Python, NoSuchElementException in Java. It usually means more dequeues than enqueues or a loop that does not stop.

    Wrong
    def serve_next(queue):    return queue.popleft()   # IndexError when empty
    Right
    def serve_next(queue):    if not queue:            # check first        return None    return queue.popleft()
  • Confusing a queue with a stack

    major

    A queue is FIFO (a line), a stack is LIFO (plates). Calling pop() on a deque takes from the rear, which turns BFS into a depth-first order and breaks shortest-path answers.

    Wrong
    node = queue.pop()        # rear: stack behaviour
    Right
    node = queue.popleft()    # front: FIFO for a queue
  • Marking BFS nodes visited when dequeued

    major

    If you only mark a node when it leaves the queue, the same node can be enqueued many times by different neighbours. Mark it when you enqueue it so each node enters the queue once.

    Wrong
    while queue:    node = queue.popleft()    seen.add(node)               # too late    for nb in graph[node]:        if nb not in seen:            queue.append(nb)     # duplicates pile up
    Right
    while queue:    node = queue.popleft()    for nb in graph[node]:        if nb not in seen:            seen.add(nb)         # mark on enqueue            queue.append(nb)
  • Circular buffer that cannot tell full from empty

    major

    With only head and tail indexes, head == tail means both empty and full. Track a count, or always keep one slot free, and wrap every index with % capacity.

    Wrong
    def is_full(self):    return self.head == self.tail   # also true when empty
    Right
    def is_full(self):    return self.count == len(self.buf)def is_empty(self):    return self.count == 0
  • Sharing a plain deque between threads

    minor

    A producer-consumer setup needs blocking and safe hand-off. queue.Queue in Python (or BlockingQueue / ConcurrentLinkedQueue in Java) handles locking and waiting for you.

    Wrong
    jobs = deque()# worker threads spin on: if jobs: jobs.popleft()
    Right
    import queuejobs = queue.Queue(maxsize=100)   # thread-safe, boundeditem = jobs.get()                 # blocks until an item arrives

Interview tips

  • How to explain it

    • A queue is a linear data structure that follows FIFO, First In, First Out, like a line at a store: the first person in line is served first.
    • Elements enter at the rear and leave from the front. The core operations are enqueue (add to rear) and dequeue (remove from front).
    • Enqueue, dequeue, peek, is_empty and size are all O(1) with a proper implementation: a deque, a linked list with head and tail, or a circular array.
    • In Python, say collections.deque with append and popleft, and mention that list.pop(0) is O(n).
  • When to reach for a queue

    • First-come, first-served order: tasks, jobs, requests, messages.
    • BFS on graphs and trees, level-order traversal, shortest path in an unweighted graph.
    • Multi-source BFS: enqueue every source first (rotting oranges, walls and gates).
    • Buffering between a fast producer and a slow consumer (print spooler, message queues).
    • Sliding windows and recent-events counters: a deque drops old items from the front.
  • Memory tricks

    • FIFO: First In, First Out. The first person in line is the first to leave. Fair and orderly.
    • A water pipe: water that enters first, exits first. The pipe preserves the order.
    • Rhyme: "First to arrive, first to depart, queue keeps order from the start. Add at rear, remove from front, that is how queues do the stunt."
    • Method of loci: guests come in through the back door (enqueue) and leave through the front door (dequeue).
  • Interview checklist

    • Before dequeue or peek: is the queue empty? Use while queue: in loops.
    • BFS: mark visited when you enqueue, and process level by level with for _ in range(len(queue)) when levels matter.
    • Fixed capacity? Use a circular buffer with a count, and wrap indexes with % capacity.
    • Do not use a queue for random access, LIFO order (use a stack), frequent search, or priority order (use a priority queue).