Skip to main content
Quick Reference

Queue Cheatsheet

A queue on one page — enqueue and dequeue, and the traps around the rear, circular full checks, and BFS visits.

10 sections 10 tables 14 code snippets

First in, first out

Enqueue at the right

dq.append(3)

Dequeue from the left

dq.popleft()

The rule

IdeaMeaning
FIFOThe first value enqueued is the first value dequeued
RearThe end where enqueue adds
FrontThe end where dequeue removes, and where peek looks
Underflowdequeue or peek when the queue is empty
Overflowenqueue when a fixed queue is already full
OrderValues leave in the same order they entered

This page is a queue. A linked list is left out.

Operations

Peek leaves the front in place

front = dq[0]

Cost at the right ends

OpCost
enqueueO(1) at the rear of a circular array, a linked queue, or a deque
dequeueO(1) at the front of those same builds
peekO(1). The front stays
list.pop(0)O(n). The front leaves, and every later item shifts
searchO(n). A queue has no random access
spaceO(n) for the values waiting

Circular array

One cell stays unused

# full when (rear + 1) % n == front

Wrap the indexes

CheckMeaning
frontIndex of the next item to dequeue
rearIndex of the next empty slot to fill
emptyfront == rear, in the version that leaves one slot unused
full(rear + 1) % capacity == front
usablecapacity - 1. The spare cell is how empty and full stay different
size counterA separate count can use every cell. full is then size == capacity

deque and Queue

The slow front

# list.pop(0) removes the front and is O(n)

A full deque drops items

# deque(maxlen=n) drops the other end when it is full

Which object

ToolMeaning
appendEnqueue at the right of a deque
popleftDequeue from the left. With append, that pair is FIFO
dq[0]Peek the front. dq[-1] is the rear
listappend plus pop(0) is FIFO, and the pop is O(n)
maxlenA new append on a full bounded deque drops the opposite end. It does not raise
queue.QueueThread-safe. get waits when empty. get_nowait raises queue.Empty

Breadth-first search

Mark early

# mark a node visited when it is enqueued

One level

width = len(dq)

Why the queue

RuleMeaning
ContainerA queue explores in discovery order. A stack would go depth first
VisitMark a node when you enqueue it, so it cannot be queued again
Late markMarking on dequeue lets the same node enter from several parents
LevelSnapshot len(dq), then dequeue that many. Those nodes are one level
StartEnqueue the source already marked visited
CostEach node enters once and each edge is checked once. O(n + e)

Priority is not FIFO

Smallest, not oldest

# heappop returns the smallest, not the oldest

A different order

ToolMeaning
heapqA min-heap. heappop returns the smallest item
Not FIFOAn older large item waits behind a newer small one
TiesPush an increasing counter as a second key when equals must keep arrival order
PriorityQueueThe thread-safe heap. Same order. Still not arrival order
heap[0]The smallest item, without removing it
Arrival orderUse a deque when the oldest item must leave first

Sliding-window maximum

Drop smaller backs

while window and nums[window[-1]] <= nums[i]:
    window.pop()

Indexes, largest at the front

StepRule
StoreIndexes, so you can tell when one has left the window
BackWhile the back value is <= the new value, pop it. The newer index stays longer
FrontIf the front index is <= i - k, it is outside the window. Pop it from the left
AnswerThe front index holds the maximum of the current window
First answerWait until the window has k items
CostEach index is pushed once and popped at most once. O(n)

Where queues show up

The person at the front leaves

# a ticket line serves the front first

The same FIFO idea

JobHow the queue helps
LineWhoever arrived first is served first
BFSNeighbors wait in the order they were found
LevelsOne snapshot of the length is one level of a tree
BufferA fast producer enqueues. A slow consumer dequeues
TasksA simple ready queue runs jobs in arrival order. A priority scheduler is a heap
Window maxA deque keeps candidate indexes, with the largest at the front

Interview traps

Both calls on the right end

# append and pop, with no left end, are a stack

Nothing at the front

# popleft on an empty deque raises IndexError

Traps worth memorising

TrapWhat happensPrefer
append and popBoth touch the right end, so the latest value leaves firstpopleft to dequeue
pop(0)FIFO, and every later item shiftsdeque.popleft
Empty popleftIndexErrorTest the deque first
front == rear for both statesEmpty and full look the sameLeave one cell empty, or keep a size
Visit on dequeueOne node can be enqueued many timesMark it when you enqueue
heappopReturns the smallest item, which may be the newestA deque when you need arrival order

How to use this page: enqueue with append, dequeue with popleft, and mark a BFS node when it enters the queue.