Queues and Deques

How queues and deques work, how to make removal from the front O(1), and what interviewers ask about queues, circular buffers and sliding windows.

12 minLesson 3 of 4
On this page
  1. How a queue works
  2. Making dequeue O(1)
  3. Variants
  4. Pitfalls
  5. In the interview
  6. What to practise next

A queue is a collection that returns items in the order they were added: the first item in is the first item out (FIFO). It is used whenever work must be handled in arrival order, and it is the structure that drives breadth-first search. A deque (double-ended queue) is a queue that also lets you add and remove at the other end, and you use it when you need both behaviours or when you need to keep a sliding window of recent items.

A queue is the opposite of a stack, which returns the newest item first. If you used a stack where a queue is needed, the most recently added task would always be served first and the oldest task could wait forever.

How a queue works

A queue has two main operations. Enqueue adds an item at the back, and dequeue removes and returns the item at the front. Most implementations also have a peek operation that reads the front item without removing it, and a check for whether the queue is empty. All of these should take O(1) time.

As a small example, consider round-robin scheduling, where one processor is shared by several jobs. The processor takes the job at the front of the queue, runs it for one unit of work, and then puts the job at the back of the queue if it still has work left. Suppose job A needs 3 units, job B needs 1 unit and job C needs 2 units. The trace shows the queue after each turn.

Round robin with jobs A:3, B:1, C:2Use the arrows or ← → keys
while queue is not empty:  job = dequeue()  run job for 1 unit, time += 1  if job has work left: enqueue(job)  else: record (job, time)
  1. queue (front on the left)
    0A:3front
    1B:1
    2C:2
    finished
    time
    0

    1The jobs wait in arrival order with the front on the left, and each cell shows a job and the units of work it still needs.

  2. queue (front on the left)
    0B:1front
    1C:2
    2A:2
    finished
    time
    1
    ran
    A

    2Job A runs for one unit and still needs 2 more, so it goes to the back of the queue behind C.

  3. queue (front on the left)
    0C:2front
    1A:2
    finished
    0B@2
    time
    2
    ran
    B

    3Job B runs and finishes at time 2.

  4. queue (front on the left)
    0A:2front
    1C:1
    finished
    0B@2
    time
    3
    ran
    C

    4Job C runs for one unit and has 1 unit left, so it goes to the back of the queue.

  5. queue (front on the left)
    0C:1front
    1A:1
    finished
    0B@2
    time
    4
    ran
    A

    5Job A runs again and has 1 unit left, so it goes to the back of the queue.

  6. queue (front on the left)
    0A:1front
    finished
    0B@2
    1C@5
    time
    5
    ran
    C

    6Job C runs its last unit and finishes at time 5.

  7. queue (front on the left)
    finished
    0B@2
    1C@5
    2A@6
    time
    6
    turns
    6

    7Job A finishes at time 6 and the queue is empty. The six units of work took six turns, and each turn was one dequeue plus at most one enqueue.

1 / 7

Making dequeue O(1)

The obvious way to build a queue is with an array, using push to enqueue and shift to dequeue (append and pop(0) in Python). This gives correct answers but can be slow, because removing the first element of an array may move every other element one slot to the left, as described in Arrays. Python's pop(0) always does this. JavaScript engines sometimes avoid the move for small arrays, but you cannot rely on it for large ones. Each dequeue then costs O(n), and emptying a queue of n items costs O(n²).

There are three standard ways to avoid this.

  • A head index. You never remove anything from the array. An index head marks the current front, and dequeue reads queue[head] and adds 1 to head. This is fast, but the slots before head are never freed.
  • A linked list with a tail pointer. Dequeue removes the head node and enqueue attaches a new node after the tail, so both are O(1), as described in Linked Lists.
  • The library's deque. Python has collections.deque. JavaScript has no built-in queue type, so the head index is the usual choice.

The round-robin simulation below uses a head index in JavaScript and deque in Python.

// jobs: list of [name, units of work]. Each turn gets 1 unit.
function roundRobin(jobs) {
  const queue = jobs.map(([name, left]) => ({ name, left }));
  let head = 0; // index of the front of the queue
  let time = 0;
  const finished = [];
  while (head < queue.length) {
    const job = queue[head];
    head++;                 // dequeue: O(1), nothing shifts
    job.left--;
    time++;
    if (job.left > 0) queue.push(job); // not done: back of the line
    else finished.push([job.name, time]);
  }
  return finished;
}
 
roundRobin([["A", 3], ["B", 1], ["C", 2]]);
// [["B", 2], ["C", 5], ["A", 6]]
from collections import deque
 
# jobs: list of (name, units of work). Each turn gets 1 unit.
def round_robin(jobs):
    queue = deque([name, left] for name, left in jobs)
    time = 0
    finished = []
    while queue:
        job = queue.popleft()  # dequeue: O(1)
        job[1] -= 1
        time += 1
        if job[1] > 0:
            queue.append(job)  # not done: back of the line
        else:
            finished.append((job[0], time))
    return finished
 
round_robin([("A", 3), ("B", 1), ("C", 2)])
# [('B', 2), ('C', 5), ('A', 6)]
ApproachTimeSpaceWhy
Array with shift / pop(0)O(n) per dequeueO(n)Every remaining item moves one slot to the left.
Array with a head indexO(1) per operationO(total enqueued)Dequeued slots are never reused.
Linked list or dequeO(1) per operationO(n)Memory follows the current contents.

Variants

Deque

A deque lets you add and remove at both ends in O(1). A stack and a queue are both special cases of a deque in which one or both ends are restricted. You need the extra end when an algorithm removes from the back as well as the front, which is what the sliding-window technique below does.

3 8 5 1 front back push front pop front push back pop back
A deque supports four O(1) operations: push and pop at the front, and push and pop at the back.

Python's deque supports all four operations directly. In JavaScript, an array with a head index supports pushing and popping at the back and popping at the front, but not pushing at the front. A full deque in JavaScript needs a ring buffer or a doubly linked list, although most algorithms never need to push at the front.

OperationPython dequeJavaScript array with a head index
push backd.append(x)a.push(x)
pop backd.pop()a.pop(), only while head < a.length
pop frontd.popleft()a[head++]
push frontd.appendleft(x)not supported
peek front or backd[0], d[-1]a[head], a[a.length - 1]

Monotonic deque for sliding-window maximum

Suppose you need the maximum of every window of k consecutive numbers in an array. Scanning each window costs O(n·k). A deque brings this down to O(n) by storing indexes of candidates whose values decrease from front to back. When a new number arrives, you pop from the back every index whose value is smaller than the new one, because those numbers can never be the maximum while the new number is in the window. Then you push the new index at the back. If the index at the front has fallen out of the window, you pop it from the front. The maximum of the current window is always the value at the front. Each index is pushed once and popped at most once, which gives the O(n) total. The same idea with a stack is covered in Monotonic Stack.

Circular queue (ring buffer)

A circular queue stores its items in a fixed-size array of capacity k and treats the end of the array as connected to the start. It keeps the index of the front and a count of the items. Enqueue writes at position (head + count) % k and dequeue moves head to (head + 1) % k. No items ever move, and slots are reused, so memory stays fixed. It is the right choice when you want a bounded buffer, such as the most recent k events. The cost is that the queue can be full, so enqueue must either fail or overwrite the oldest item.

Priority queue

A priority queue is not a variant of FIFO. It returns the item with the highest priority, not the oldest one, and it is built on a heap. If a problem asks for the smallest, largest or most urgent item rather than the oldest one, use a priority queue instead of a queue.

When a queue does not apply

A queue does not help when you need to look up an item by value or remove an item from the middle, because it only gives you access to the ends. Use a hash table for lookups. If the most recent item must be handled first, as in undo or matching brackets, you need a stack.

Pitfalls

In the interview

A queue is the likely answer when the problem asks you to process things in the order they arrived, or to explore something level by level or by the fewest steps. Phrases such as "shortest path in an unweighted graph", "minimum number of moves", "process in rounds", "the most recent k events" and "maximum in every window of size k" all point to a queue or deque. In an interview, say which end you add to and which end you remove from, and say which structure you will use so that dequeue is O(1).

These are the questions interviewers commonly ask.

Why not use an array and remove from the front? Removing the first element of an array shifts the rest, so each dequeue can cost O(n) and a loop that empties the queue costs O(n²). A deque, a linked list or a head index makes each dequeue O(1). Interviewers ask this to check that you know what a library call costs.

How would you build a queue from two stacks? Keep an input stack and an output stack. Enqueue pushes onto the input stack. Dequeue pops from the output stack, and if the output stack is empty, it first moves every item from the input stack to the output stack, which reverses their order so the oldest item is on top. A single dequeue can cost O(n), but each item is moved at most once, so the amortised cost per operation is O(1). The practice problem Two-Spike Order Rail asks for this.

How would you build a stack from queues? With one queue, you enqueue the new item and then dequeue and re-enqueue every item that was there before it, so the new item ends up at the front. Push then costs O(n) and pop costs O(1). The same trade-off can be moved to pop instead. Neither version is efficient, which is why this question is mainly about showing that you can reason about the order of items.

How do you design a fixed-size circular queue? Use an array of capacity k, a head index and a count. Enqueue is allowed only when the count is less than k and writes at (head + count) % k. Dequeue is allowed only when the count is above 0 and advances the head by one modulo k. Storing the count, rather than comparing head and tail indexes, avoids the ambiguity between a full and an empty queue, which look the same when the two indexes are equal.

How do you find the maximum of every window of size k in O(n)? Use the monotonic deque described above. Each index enters the deque once and leaves it at most once, so the total work is O(n) even though one step may pop several items. Interviewers usually follow up by asking why a heap is slower, and the answer is that a heap costs O(log n) per operation and gives O(n log n) overall.

Which structure do you use for breadth-first search, and why? A queue, because it visits nodes in order of their distance from the start: all nodes one step away before any node two steps away. That order is what makes the first time you reach a node the shortest path in an unweighted graph. A stack would give depth-first search, which does not have this property.

Quick check

Start with an empty queue. Enqueue 4, enqueue 9, dequeue, enqueue 1, enqueue 6, dequeue. What is at the front now?

A JavaScript function processes a list of n tasks with while (tasks.length) handle(tasks.shift()), and handle takes O(1). What is the total cost?

Which job needs a deque rather than a plain queue or stack?

What to practise next

Try Two-Spike Order Rail, which builds a queue from two stacks, and then use a queue in Breadth-First Search. After that, Monotonic Stack shows how to keep a stack in sorted order to answer "next bigger" questions in O(n).