Simple Algorithm
Algorithms & Data Structures · Optimized · 20 min

Stacks, Queues & Deques

Last in, first out; first in, first out; and both ends at once.

Every function call your program makes pushes a frame onto a stack, and every page a web crawler discovers waits its turn in a queue. Both structures do less than an array: you may touch only one end, or two. That restriction is exactly what makes every operation O(1)O(1), and every algorithm built on them easy to prove correct.

What you’ll learn

  • Implement a stack on a dynamic array or a linked list and a queue on a circular buffer, and state each operation's cost as worst case or amortized.
  • Tell a full circular buffer from an empty one, and grow one without scrambling the order of its items.
  • Prove a stack algorithm correct with an invariant (bracket matching), and trace postfix evaluation.
  • Replace recursion with an explicit stack, run BFS with a queue, and explain why swapping one container for the other does not turn BFS into DFS.
  • Pick the right container in Python and C++, and recognize problems that call for a stack, a queue or a deque.

Three ways to restrict access

An abstract data type says what the operations do, not how the data is stored. Three of the most useful ones restrict where you may touch a sequence:

  • A stack adds and removes at one end only, the top: push(x), pop(), top(). The last item in is the first out (LIFO).
  • A queue adds at the back and removes at the front: enqueue(x), dequeue(), front(). The first item in is the first out (FIFO).
  • A deque (a double-ended queue, pronounced "deck") adds and removes at both ends.

Giving up the middle buys simplicity. Each operation touches one or two cells, so it costs O(1)O(1), and the order of the items is fixed by the order of the operations, which is what every correctness proof below relies on.

ImplementationOperationsCostTrade-off
Stack on a dynamic array, top at the endpush, pop, toppush O(1)O(1) amortized (a resize copies all nn items, Θ(n)\Theta(n), once in a while); pop O(1)O(1)Contiguous and cache-friendly: the usual choice
Stack on a singly linked list, top at the headpush, pop, topO(1)O(1) worst caseOne allocation and one pointer per item
Queue on a circular bufferenqueue, dequeue, frontO(1)O(1) worst case at a fixed capacity; O(1)O(1) amortized if it growsContiguous, but telling full from empty needs care
Queue on a linked list with head and tail pointersenqueue at the tail, dequeue at the headO(1)O(1) worst casePointer chasing and one allocation per item
Deque on a growable circular bufferpush and pop at both endsO(1)O(1) amortized at both endsJava's ArrayDeque works this way
python
class LinkedStack:
    def __init__(self):
        self.head = None              # each node is a pair (value, next)
        self.n = 0

    def push(self, x):                # O(1) worst case: one new node
        self.head = (x, self.head)
        self.n += 1

    def pop(self):
        if self.head is None:
            raise IndexError("pop from empty stack")
        x, self.head = self.head
        self.n -= 1
        return x

A linked stack with tuples as nodes. A Python list used with append and pop is the array-based stack, and it is usually faster, because its items sit in one block of memory.

Think first A real-time audio callback pushes onto a stack, and no single push may ever take more than a constant amount of time. Which implementation guarantees that: a dynamic array that doubles when full, or a linked list?

The linked list, ideally with nodes taken from a pool allocated in advance, so that not even the memory allocator can stall. A doubling array is O(1)O(1) only amortized: averaged over any sequence of pushes the cost is constant, but the push that triggers a resize copies all nn items. A deadline is about the worst case.

Queues in an array: the circular buffer

A queue stored in a plain array with its front always at index 0 must shift every remaining item on each dequeue: Θ(n)\Theta(n) per operation. The fix is to leave the items where they are and move the ends instead. Keep the index head of the front item and a count size. With capacity cc, the items in queue order are

buf[(head+i) mod c],i=0,1,…,size−1.\texttt{buf}[(\texttt{head} + i) \bmod c], \qquad i = 0, 1, \dots, \texttt{size} - 1.

Dequeue reads slot head and advances it; enqueue writes slot (head+size) mod c(\texttt{head} + \texttt{size}) \bmod c. Both keep this invariant, so items leave in the order they arrived, and both indices wrap past the end of the array as if it were a ring.

Predict before you look

A circular buffer with capacity 8 uses fix 2: one slot always stays empty. Its head is 6 and its tail (the next free slot) is 3. How many items does it hold?

Show the answer

5 items

(3−6) mod 8=5(3 - 6) \bmod 8 = 5: the items sit in slots 6, 7, 0, 1 and 2, wrapping past the end. A size of 8 is impossible under this convention, since at most 7 of the 8 slots are ever used.

python
class RingQueue:
    def __init__(self, capacity=4):
        self.buf = [None] * capacity
        self.head = 0                  # slot of the front item
        self.size = 0                  # the count settles full versus empty

    def enqueue(self, x):
        if self.size == len(self.buf):  # full: double, unrolling the ring
            old, n = self.buf, len(self.buf)
            self.buf = [old[(self.head + i) % n] for i in range(n)] + [None] * n
            self.head = 0
        self.buf[(self.head + self.size) % len(self.buf)] = x
        self.size += 1

    def dequeue(self):
        if self.size == 0:
            raise IndexError("dequeue from empty queue")
        x = self.buf[self.head]
        self.buf[self.head] = None      # drop the reference
        self.head = (self.head + 1) % len(self.buf)
        self.size -= 1
        return x

When the buffer is full it doubles, and the copy must unroll the ring, front item first. Copying the raw array instead leaves the wrapped-around items in the wrong place: after a wrap, the old front would no longer be followed by its successors. Each operation is O(1)O(1) amortized, by the same argument as for a dynamic array.

Matching brackets with a stack

Is {[()()]} balanced? Is ([)]? A brute-force check deletes adjacent matching pairs such as () until none are left and accepts if nothing remains: up to n/2n/2 passes of O(n)O(n) each, so O(n2)O(n^2). A stack does it in one pass. Scan left to right and push each opener; on a closer, the top of the stack must be its partner, which you pop; at the end the stack must be empty.

python
PAIRS = {')': '(', ']': '[', '}': '{'}

def balanced(s):
    stack = []
    for ch in s:
        if ch in '([{':
            stack.append(ch)
        elif ch in PAIRS:
            if not stack or stack.pop() != PAIRS[ch]:
                return False          # a closer with no partner, or the wrong one
    return not stack                  # leftover openers are unmatched

One pass: O(n)O(n) time, and O(n)O(n) extra space in the worst case (a string of openers). Other characters are skipped.

DerivationProof: an invariant on the stack
  1. p=u1 o1 u2 o2⋯uk ok uk+1p = u_1\, o_1\, u_2\, o_2 \cdots u_k\, o_k\, u_{k+1}

    Invariant. If the scan has read a prefix pp of ss without failing, then pp splits as below, where every uju_j is balanced and o1,…,oko_1, \dots, o_k are exactly the openers on the stack, bottom to top. At the start, p=εp = \varepsilon and k=0k = 0.

  2. p o=u1 o1⋯uk ok uk+1  o  εp\, o = u_1\, o_1 \cdots u_k\, o_k\, u_{k+1}\; o\; \varepsilon

    An opener oo is pushed, and the invariant holds with k+1k + 1 openers and an empty balanced string after the new one.

  3. uk ok uk+1 c is balanced, so p c=u1 o1⋯ok−1 (uk ok uk+1 c)u_k\, o_k\, u_{k+1}\, c\ \text{is balanced, so } p\,c = u_1\, o_1 \cdots o_{k-1}\, \big(u_k\, o_k\, u_{k+1}\, c\big)

    A closer cc that is oko_k's partner makes okuk+1co_k u_{k+1} c balanced, hence uk okuk+1cu_k\, o_k u_{k+1} c too, and popping oko_k restores the invariant with k−1k - 1 openers. If cc is not oko_k's partner, or the stack is empty, then no completion of p cp\,c is balanced: in a balanced string every closer matches the nearest unmatched opener before it, and here that opener is oko_k, or there is none. So returning False is right.

  4. s is balanced  ⟺  k=0  ⟺  the stack is emptys\ \text{is balanced} \iff k = 0 \iff \text{the stack is empty}

    At the end, s=u1o1⋯okuk+1s = u_1 o_1 \cdots o_k u_{k+1}, which is balanced exactly when no opener is left over.

Check your understanding

For which string does the algorithm reject only after reading the whole string?

  1. ([)]
  2. ())(
  3. (()
  4. )(
Show the answer

C. (()

In (() the closer finds its partner on top, so the scan reaches the end, and only the final check sees an opener left over. ([)] fails at its ), which finds [ on top; ())( fails at its second ), which finds the stack empty; )( fails at once.

Think first The same stack evaluates postfix expressions, in which each operator follows its two operands. Evaluate 6 2 3 + * 4 -: push each number; an operator pops two values and pushes its result.

The stack evolves as [6][6], [6,2][6, 2], [6,2,3][6, 2, 3], [6,5][6, 5], [30][30], [30,4][30, 4], [26][26], so the value is 6×(2+3)−4=266 \times (2 + 3) - 4 = 26. Postfix needs no parentheses and no precedence rules. The Optimal lesson Parsing Expressions with Stacks turns ordinary infix notation into postfix with Dijkstra's shunting-yard algorithm, again with a single stack.

The call stack, DFS and BFS

Your programs already use a stack. Each function call pushes a stack frame (arguments, local variables, the return address) onto the call stack, and each return pops it. Recursion is a stack in disguise, and a recursion that goes too deep runs out of room: a stack overflow. CPython stops at a default depth of 1000 frames (sys.getrecursionlimit()); compiled languages get a fixed stack, typically a few megabytes, whose size depends on the system.

So a recursive depth-first search down a path of 10610^6 vertices crashes. The cure is to keep the stack yourself, on the heap, where it can grow:

python
from collections import deque

def dfs_iterative(adj, s):
    seen, order, stack = set(), [], [s]
    while stack:
        v = stack.pop()
        if v in seen:
            continue                  # a stale entry: v was reached another way first
        seen.add(v)
        order.append(v)
        for w in reversed(adj[v]):    # reversed, so neighbors are visited in list order
            if w not in seen:
                stack.append(w)
    return order

def bfs(adj, s):
    seen, order, queue = {s}, [], deque([s])
    while queue:
        v = queue.popleft()
        order.append(v)
        for w in adj[v]:
            if w not in seen:
                seen.add(w)           # mark on enqueue: each vertex enters once
                queue.append(w)
    return order

Both take O(n+m)O(n + m) time on nn vertices and mm edges. dfs_iterative visits vertices in the same order as the recursive version because it marks a vertex when it is popped: the deepest vertex that reaches it claims it. The price is that a vertex can sit on the stack once per edge that reaches it before its visit, so the stack holds O(m)O(m) entries in the worst case. BFS marks on enqueue, so its queue holds at most nn.

Two more stacks you use every day. An editor keeps an undo stack of actions: each new action is pushed, and undo pops it onto a redo stack, from which redo pops it back. A new action clears the redo stack, since the future it recorded no longer exists.

And two stacks make a queue. Push onto an in stack; to dequeue, pop from an out stack, refilling it by moving the whole in-stack over (which reverses it) whenever it runs empty. Each item is moved at most once, so any mm operations cost O(m)O(m) in total: O(1)O(1) amortized, although one unlucky dequeue costs Θ(n)\Theta(n). The Optimal lesson Queues from Stacks: Amortized & Real-Time proves this and then removes the Θ(n)\Theta(n) spike.

Think first In an editor you type A, then B, then C, press undo twice, then type D. What does redo do now?

Nothing. After the two undos, the undo stack holds A and the redo stack holds C and B, with B on top. Typing D pushes D onto the undo stack and clears the redo stack, because B and C were edits of a text that no longer exists.

The containers you will actually use

ContainerUse it asCostsWatch out for
Python lista stack: append, pop()O(1)O(1) amortized at the endpop(0) and insert(0, x) shift every other item: Θ(n)\Theta(n)
Python collections.dequea queue or deque: append, popleft, appendleft, popO(1)O(1) at both endsIndexing is O(1)O(1) near the ends but O(n)O(n) in the middle: it is a linked list of fixed-size blocks
C++ std::stack, std::queueadapters with push, pop, top or frontO(1)O(1) (amortized when the underlying container reallocates)Built on std::deque by default; pop() returns nothing, so read top() or front() first
C++ std::dequea deque with indexingO(1)O(1) at both ends, O(1)O(1) indexingNot contiguous: fixed-size blocks plus an index of the blocks
Java ArrayDequea stack or a queueO(1)O(1) amortized at both endsPreferred over the legacy Stack class and over LinkedList
Think first You empty a 100,000-item Python list by calling pop(0) until it is empty. Roughly how many item moves does that cost in total?

Popping the front of a list of length LL shifts the other L−1L - 1 items, so the total is 99,999+99,998+⋯+1+0=n(n−1)/2≈5×10999{,}999 + 99{,}998 + \dots + 1 + 0 = n(n - 1)/2 \approx 5 \times 10^9. On a laptop that takes seconds; deque.popleft() empties the same 100,000 items in milliseconds.

A priority queue, which always releases the most urgent item rather than the oldest, is a different abstract data type. It is usually built on a heap (heapq in Python, std::priority_queue in C++) with O(log⁡n)O(\log n) operations, and it belongs to the Trees & Heaps topic.

Recognizing it

The signals in a problem statement:

  • Stack: nested structure (brackets, tags, expressions); "the most recent" (undo, backtracking); pairing each item with the nearest unmatched one before it; recursion that must become iterative.
  • Queue: "in the order they arrived", fairness, a simulated waiting line; levels, or the fewest steps in an unweighted graph (BFS); "in the last tt seconds".
  • Deque: work at both ends; sliding windows (the next lesson's monotonic deque); shortest paths when edges weigh 0 or 1.
Problem (in brief)StructureKey ideaCost
Is a string of ()[]{} balanced?stackeach closer must match the most recent unmatched openerO(n)O(n)
Simplify a file path such as /a/./b/../../c/stacka directory name is pushed, .. pops one, . is skipped; here the result is /cO(n)O(n)
A stack that also reports its minimumtwo stacksbeside each item, push the minimum of everything at or below itO(1)O(1) per operation
At each new request, how many requests arrived in the last 3000 ms?queueenqueue the new time; dequeue from the front while the front is older than the window; the answer is the lengthO(1)O(1) amortized
The fewest moves through a grid mazequeueBFS reaches cells in order of distanceO(rows⋅cols)O(\text{rows} \cdot \text{cols})
Shortest paths when every edge weighs 0 or 1deque0-1 BFS: a vertex reached by a weight-0 edge goes to the front, by a weight-1 edge to the backO(n+m)O(n + m)
A look-alike: "serve the most urgent job first" sounds like a queue, but the order is by priority, not by arrival. That is a priority queue (a heap, O(log⁡n)O(\log n) per operation); a FIFO queue would serve the wrong job.
Check your understanding

Customers join a line and are served from the front. A customer may also give up and leave, but only the last one in line ever does. Which structure fits?

  1. A stack
  2. A queue
  3. A deque
  4. A priority queue
Show the answer

C. A deque

Serving removes from the front and giving up removes from the back, so you need removal at both ends, plus insertion at the back: a deque, O(1)O(1) per operation.

Key takeaways

  • Stacks (LIFO), queues (FIFO) and deques allow access only at the ends, so every operation is O(1)O(1) and the order of the items follows from the order of the operations.
  • On arrays they are O(1)O(1) amortized and cache-friendly (a dynamic array, a circular buffer); on linked lists they are O(1)O(1) in the worst case. A circular buffer needs a count, or one empty slot, to tell full from empty.
  • A stack pairs each item with the most recent unmatched one: brackets, postfix, undo, the call stack and DFS. A queue processes items in arrival order: BFS levels, buffers and time windows.
  • In Python, use a list as a stack and collections.deque as a queue, never list.pop(0); in C++, std::stack and std::queue wrap std::deque by default.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A circular-buffer queue stores only head (the front item's slot) and tail (the next free slot), and every slot may be used. After some operations, head == tail. What do you know?

  1. The queue is empty
  2. The queue is full
  3. Nothing yet: it is either empty or full, so the implementation needs a count or must keep one slot free
  4. The buffer must be resized before the next operation
Show the answer

C. Nothing yet: it is either empty or full, so the implementation needs a count or must keep one slot free

With cc slots there are c+1c + 1 possible sizes (00 to cc) but only cc values of (tail - head) mod c, so the empty and the full queue collide at head == tail. Storing the size, or capping it at c−1c - 1, removes the collision.

Question 2

A BFS written in Python dequeues with queue.pop(0) on a list, and it is far too slow on a graph with 10510^5 vertices. What is wrong, and what fixes it?

  1. BFS is quadratic by nature; switch to DFS
  2. pop(0) shifts every remaining item, Θ(n)\Theta(n) per dequeue; use collections.deque and popleft()
  3. Python lists are linked lists, so pop(0) must walk the list; use an array instead
  4. The seen set is the bottleneck; replace it with a list
Show the answer

B. pop(0) shifts every remaining item, Θ(n)\Theta(n) per dequeue; use collections.deque and popleft()

A Python list is a dynamic array: removing its first item moves every other item one slot left, so nn dequeues cost Θ(n2)\Theta(n^2) in total. A deque removes from the front in O(1)O(1), and BFS is O(n+m)O(n + m) again.

Question 3

You take a BFS that marks vertices when they are enqueued and replace its queue by a stack, changing nothing else. What do you get?

  1. A traversal that reaches every reachable vertex once, but in general not in any depth-first order
  2. Exactly the visiting order of recursive DFS
  3. The BFS order, reversed
  4. An infinite loop on graphs with cycles
Show the answer

A. A traversal that reaches every reachable vertex once, but in general not in any depth-first order

Marking on push lets the first vertex that sees a neighbor claim it, whereas DFS lets the deepest vertex that reaches it claim it. On the edges 0–1, 0–2, 0–3 and 1–3, starting at 0, the stack version visits 0, 3, 2, 1, which no depth-first search produces. True DFS with an explicit stack marks a vertex when it is popped.

Question 4

A stack is stored in a dynamic array that doubles its capacity when full. What does a push cost?

  1. O(1)O(1) in the worst case
  2. O(log⁡n)O(\log n), because of the doublings
  3. Θ(n)\Theta(n) amortized, because a resize copies everything
  4. O(1)O(1) amortized, and Θ(n)\Theta(n) in the worst case, for the push that triggers a resize
Show the answer

D. O(1)O(1) amortized, and Θ(n)\Theta(n) in the worst case, for the push that triggers a resize

A resize copies all the items, but resizes happen only at sizes 1,2,4,8,…1, 2, 4, 8, \dots, so mm pushes copy fewer than 2m2m items in total: O(1)O(1) per push averaged over any sequence, which is what amortized means. The single push that triggers a resize still costs Θ(n)\Theta(n).

Question 5

Every edge of a graph weighs 0 or 1. Which container lets a BFS-like search compute all shortest distances from a source in O(n+m)O(n + m) time?

  1. A stack
  2. A queue
  3. A priority queue
  4. A deque
Show the answer

D. A deque

In 0-1 BFS, a vertex reached by a weight-0 edge goes to the front of the deque (same distance) and one reached by a weight-1 edge to the back (distance plus one). The deque then holds vertices in nondecreasing order of distance, with at most two distinct values: the order Dijkstra's priority queue would give, without its O(log⁡n)O(\log n) factor.

Go deeper

Further reading

  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 10.
  • R. Sedgewick & K. Wayne, Algorithms, 4th ed. (Addison-Wesley, 2011), section 1.3.
  • D. E. Knuth, The Art of Computer Programming, Vol. 1: Fundamental Algorithms, 3rd ed. (Addison-Wesley, 1997), section 2.2.1.