Back to all posts

Queue

4 min read
data-structuresqueuecs-fundamentalsinterview-prep

FIFO (First In, First Out) data structure. The first element enqueued is the first dequeued. Think: task scheduling, BFS, message queues (Kafka, RabbitMQ).

Core Structure

text
Queue:
  data[]
  front = 0
  rear  = -1

enqueue(val):  data[++rear] = val
dequeue():     return data[front++]
peek():        return data[front]
isEmpty():     return front > rear

Core Operations

OperationDescriptionTimeSpace
enqueue(val)Add to rearO(1)O(1)
dequeue()Remove from frontO(1)O(1)
peek()View front without removingO(1)O(1)
isEmpty()Check if emptyO(1)O(1)

Types

TypeDescriptionUse Case
Simple QueueFIFO, linearTask scheduling
Circular QueueRear wraps to frontBuffer, fixed-size pool
Deque (Double-ended)Insert/remove from both endsSliding window problems
Priority QueueDequeue by priority, not orderDijkstra, heap-based

Circular Queue

Avoids wasted space in array-backed queues by wrapping indices.

text
enqueue(val):
  if isFull(): throw overflow
  rear = (rear + 1) % capacity
  data[rear] = val

dequeue():
  if isEmpty(): throw underflow
  val = data[front]
  front = (front + 1) % capacity
  return val

isFull():  return (rear + 1) % capacity == front
isEmpty(): return front == rear
TimeSpace
ComplexityO(1)O(n)

Queue via Two Stacks

Implement queue using two stacks — common interview problem.

text
enqueue(val):  stack1.push(val)

dequeue():
  if stack2.isEmpty():
    while stack1 not empty:
      stack2.push(stack1.pop())
  return stack2.pop()
EnqueueDequeue (amortized)
TimeO(1)O(1) amortized

Elements are moved from stack1 to stack2 only when stack2 is empty — each element moves once total.


BFS with Queue

Queue is the backbone of Breadth-First Search — processes nodes level by level.

text
bfs(root):
  queue = [root]
  while queue not empty:
    node = queue.dequeue()
    visit(node)
    for each neighbor of node:
      if not visited: queue.enqueue(neighbor)
TimeSpace
ComplexityO(V + E)O(V)

Priority Queue (Heap-backed)

Elements dequeued by priority, not insertion order. Backed by a min-heap or max-heap.

text
// Min-heap priority queue
enqueue(val, priority): heap.insert(val, priority)
dequeue():              return heap.extractMin()
peek():                 return heap.min()
OperationTime
enqueueO(log n)
dequeueO(log n)
peekO(1)

Java: PriorityQueue<> is a min-heap by default. Pass a custom comparator for max-heap or custom ordering.


Deque (Double-Ended Queue)

Supports insert and remove from both front and rear.

text
addFront(val)   removeFront()
addRear(val)    removeRear()
  • Use case: Sliding window maximum/minimum (monotonic deque)
  • Java: ArrayDeque — preferred over Stack and LinkedList for both stack and queue needs
OperationTime
Add/remove front or rearO(1)

Common Interview Patterns

PatternProblem Examples
BFSLevel-order traversal, shortest path
Sliding windowMax in window, moving average
Task schedulingCPU scheduling, rate limiting
Queue via stacksImplement queue with two stacks
Monotonic dequeSliding window maximum

Stack vs Queue

StackQueue
OrderLIFOFIFO
Insertpush → topenqueue → rear
Removepop ← topdequeue ← front
TraversalDFSBFS
Java classDeque / ArrayDequeQueue / ArrayDeque