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 , 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 , and the order of the items is fixed by the order of the operations, which is what every correctness proof below relies on.
| Implementation | Operations | Cost | Trade-off |
|---|---|---|---|
| Stack on a dynamic array, top at the end | push, pop, top | push amortized (a resize copies all items, , once in a while); pop | Contiguous and cache-friendly: the usual choice |
| Stack on a singly linked list, top at the head | push, pop, top | worst case | One allocation and one pointer per item |
| Queue on a circular buffer | enqueue, dequeue, front | worst case at a fixed capacity; amortized if it grows | Contiguous, but telling full from empty needs care |
| Queue on a linked list with head and tail pointers | enqueue at the tail, dequeue at the head | worst case | Pointer chasing and one allocation per item |
| Deque on a growable circular buffer | push and pop at both ends | amortized at both ends | Java's ArrayDeque works this way |
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 xA 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 only amortized: averaged over any sequence of pushes the cost is constant, but the push that triggers a resize copies all 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: 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 , the items in queue order are
Dequeue reads slot head and advances it; enqueue writes slot . 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.
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
: 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.
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 xWhen 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 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 passes of each, so . 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.
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 unmatchedOne pass: time, and extra space in the worst case (a string of openers). Other characters are skipped.
Invariant. If the scan has read a prefix of without failing, then splits as below, where every is balanced and are exactly the openers on the stack, bottom to top. At the start, and .
An opener is pushed, and the invariant holds with openers and an empty balanced string after the new one.
A closer that is 's partner makes balanced, hence too, and popping restores the invariant with openers. If is not 's partner, or the stack is empty, then no completion of is balanced: in a balanced string every closer matches the nearest unmatched opener before it, and here that opener is , or there is none. So returning
Falseis right.At the end, , which is balanced exactly when no opener is left over.
For which string does the algorithm reject only after reading the whole string?
([)]())((())(
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 , , , , , , , so the value is . 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 vertices crashes. The cure is to keep the stack yourself, on the heap, where it can grow:
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 orderBoth take time on vertices and 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 entries in the worst case. BFS marks on enqueue, so its queue holds at most .
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 operations cost in total: amortized, although one unlucky dequeue costs . The Optimal lesson Queues from Stacks: Amortized & Real-Time proves this and then removes the 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
| Container | Use it as | Costs | Watch out for |
|---|---|---|---|
Python list | a stack: append, pop() | amortized at the end | pop(0) and insert(0, x) shift every other item: |
Python collections.deque | a queue or deque: append, popleft, appendleft, pop | at both ends | Indexing is near the ends but in the middle: it is a linked list of fixed-size blocks |
C++ std::stack, std::queue | adapters with push, pop, top or front | (amortized when the underlying container reallocates) | Built on std::deque by default; pop() returns nothing, so read top() or front() first |
C++ std::deque | a deque with indexing | at both ends, indexing | Not contiguous: fixed-size blocks plus an index of the blocks |
Java ArrayDeque | a stack or a queue | amortized at both ends | Preferred 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 shifts the other items, so the total is . 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 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 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) | Structure | Key idea | Cost |
|---|---|---|---|
Is a string of ()[]{} balanced? | stack | each closer must match the most recent unmatched opener | |
Simplify a file path such as /a/./b/../../c/ | stack | a directory name is pushed, .. pops one, . is skipped; here the result is /c | |
| A stack that also reports its minimum | two stacks | beside each item, push the minimum of everything at or below it | per operation |
| At each new request, how many requests arrived in the last 3000 ms? | queue | enqueue the new time; dequeue from the front while the front is older than the window; the answer is the length | amortized |
| The fewest moves through a grid maze | queue | BFS reaches cells in order of distance | |
| Shortest paths when every edge weighs 0 or 1 | deque | 0-1 BFS: a vertex reached by a weight-0 edge goes to the front, by a weight-1 edge to the back |
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?
- A stack
- A queue
- A deque
- 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, per operation.
Key takeaways
- Stacks (LIFO), queues (FIFO) and deques allow access only at the ends, so every operation is and the order of the items follows from the order of the operations.
- On arrays they are amortized and cache-friendly (a dynamic array, a circular buffer); on linked lists they are 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
listas a stack andcollections.dequeas a queue, neverlist.pop(0); in C++,std::stackandstd::queuewrapstd::dequeby default.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
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?
- The queue is empty
- The queue is full
- Nothing yet: it is either empty or full, so the implementation needs a count or must keep one slot free
- 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 slots there are possible sizes ( to ) but only values of (tail - head) mod c, so the empty and the full queue collide at head == tail. Storing the size, or capping it at , removes the collision.
A BFS written in Python dequeues with queue.pop(0) on a list, and it is far too slow on a graph with vertices. What is wrong, and what fixes it?
- BFS is quadratic by nature; switch to DFS
pop(0)shifts every remaining item, per dequeue; usecollections.dequeandpopleft()- Python lists are linked lists, so
pop(0)must walk the list; use an array instead - The
seenset is the bottleneck; replace it with a list
Show the answer
B. pop(0) shifts every remaining item, 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 dequeues cost in total. A deque removes from the front in , and BFS is again.
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?
- A traversal that reaches every reachable vertex once, but in general not in any depth-first order
- Exactly the visiting order of recursive DFS
- The BFS order, reversed
- 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.
A stack is stored in a dynamic array that doubles its capacity when full. What does a push cost?
- in the worst case
- , because of the doublings
- amortized, because a resize copies everything
- amortized, and in the worst case, for the push that triggers a resize
Show the answer
D. amortized, and in the worst case, for the push that triggers a resize
A resize copies all the items, but resizes happen only at sizes , so pushes copy fewer than items in total: per push averaged over any sequence, which is what amortized means. The single push that triggers a resize still costs .
Every edge of a graph weighs 0 or 1. Which container lets a BFS-like search compute all shortest distances from a source in time?
- A stack
- A queue
- A priority queue
- 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 factor.
Go deeper
- Parsing Expressions with Stacks · Shunting-yard, postfix evaluation and stack machines.
- Queues from Stacks: Amortized & Real-Time · Two-stack queues, their amortized cost, and worst-case O(1) functional queues.
- Concurrent Stacks & Queues · Lock-free Treiber stacks, Michael–Scott queues and the ABA problem.
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.