Sub topic 11
Where Each Structure Fits: Stacks, Queues, LRU Caches and More
This chapter assumes you know basic Big-O notation, can follow references or pointers, and have read the earlier chapters on access cost, insertion cost, and dynamic array growth. Here we apply those costs to real workloads.
Stacks: arrays win
A stack is last-in, first-out. You only touch one end, so you need push and pop at the end. A dynamic array does both in amortized O(1), and its elements sit next to each other in memory. A linked list also gives O(1) push and pop at the head, but it allocates one node per element.
Python's list is a good stack:
stack = []
stack.append("a")
stack.append("b")
print(stack.pop()) # b
print(stack.pop()) # aUse a linked list for a stack only if you need worst-case O(1) per push. A dynamic array occasionally pays O(n) for a resize.
Queues: the front is the problem
A queue is first-in, first-out. You add at the back and remove from the front. A plain array makes removal at the front O(n), because every later element shifts left. A singly linked list with a head and a tail pointer handles both ends in O(1).
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Queue:
def __init__(self):
self.head = None
self.tail = None
def enqueue(self, value):
node = Node(value)
if self.tail is None:
self.head = self.tail = node
else:
self.tail.next = node
self.tail = node
def dequeue(self):
if self.head is None:
raise IndexError("dequeue from empty queue")
value = self.head.value
self.head = self.head.next
if self.head is None:
self.tail = None
return value
q = Queue()
q.enqueue(1)
q.enqueue(2)
print(q.dequeue()) # 1Note the line that resets tail when the queue becomes empty. Forgetting it leaves a stale pointer to a removed node.
Arrays can also make good queues. A circular buffer keeps a fixed array and two indexes that wrap around. This gives O(1) at both ends with no per-node allocation. Python's collections.deque is a related design: it stores blocks of items and links the blocks together.
LRU caches: use both
An LRU (least recently used) cache holds a limited number of entries. When it is full, it evicts the entry that was used longest ago. Each lookup must be O(1), and each use must move an entry to the "most recent" position in O(1).
Neither structure alone does this:
- A hash map finds an entry in O(1) but has no usage order.
- A doubly linked list keeps usage order and can move a node in O(1), but only if you already hold the node.
The standard design combines them. The hash map maps each key to its list node. That supplies the node reference the list needs, which is why the unlink operation from the earlier chapter runs in O(1). An array cannot do this, because moving an element to the front shifts the others.
Other common cases
| Workload | Better fit | Reason |
|---|---|---|
| Read by index, iterate often | Array | O(1) access, cache-friendly scans |
| Stack | Dynamic array | Amortized O(1) at the end |
| Queue | Linked list or circular buffer | O(1) at both ends |
| Sorted data with binary search | Array | Needs random access |
| Many splices at known positions | Doubly linked list | O(1) relink with node in hand |
| Undo history | Array or linked list | Both work; array is simpler |
| Adjacency lists in graphs | Dynamic array | Mostly appended and scanned |
Reading the pattern
Look at which operations the workload needs most often. Access by position and scanning favor arrays. Operations at both ends, or relinking nodes you already hold, favor linked structures. Many real systems, like the LRU cache, use both.
Exercise
You are building a task scheduler. Tasks are added at the back and the oldest task is always removed from the front. Why is a plain Python list a poor choice, and what would you use instead?
Show answer
Removing from the front of a list with pop(0) is O(n) because all later elements shift left. Use a linked list with head and tail pointers, a circular buffer, or collections.deque, which give O(1) at both ends.
Exercise
In an LRU cache, why must the hash map store references to list nodes rather than just the values?
Show answer
Moving an entry to the front of a doubly linked list is O(1) only when you already hold its node. The map supplies that node directly, so no O(n) search of the list is needed.