Queues and Deques

Use first-in-first-out queues for BFS and scheduling, circular buffers for fixed capacity, and double-ended queues for flexible access.

Beginner · about 3 hours · difficulty 2/5

Learn first: Stacks

A queue processes items in the order they arrive (FIFO): enqueue at the back, dequeue from the front, both O(1). A deque (double-ended queue) allows O(1) push and pop at both ends.

Where queues appear

  • Breadth-first search: the queue holds the frontier, which is why BFS finds shortest paths in unweighted graphs.
  • Level order traversal of trees.
  • Scheduling and simulation: round-robin CPU scheduling, task processing, "Number of Recent Calls".
  • Producer-consumer buffers in operating systems and message queues in system design.

Implementations

  • Circular array: keep head and tail indices modulo capacity. Design Circular Queue is a common interview and lab exercise; the tricky part is distinguishing full from empty (track a count or leave one slot unused).
  • Linked list with head and tail pointers.
  • Library: std::queue/std::deque, ArrayDeque in Java, collections.deque in Python.

Related puzzles

Implement a queue using two stacks (amortized O(1) per operation) and a stack using queues. These test whether you understand amortized analysis.

Pitfall: using a Python list with pop(0) or a Java ArrayList.remove(0) as a queue, which is O(n) per dequeue.

Key concepts

  • FIFO operations
  • Circular queue on an array
  • Deque operations
  • Queue using two stacks
  • Queues in BFS and scheduling

Mini project

Implement a circular queue from scratch, then solve: Design Circular Queue, Implement Queue using Stacks, Implement Stack using Queues, Number of Recent Calls, Dota2 Senate, and Time Needed to Buy Tickets.

Check yourself

Why does implementing a queue with two stacks give amortized O(1) dequeue even though a single dequeue can move n elements?

Free resources