Sub topic 12
A practical framework for choosing
This chapter assumes you know basic Big-O notation, understand references or pointers, and have read the earlier chapters on memory layout, access costs, insertion and deletion, dynamic array growth, cache locality, memory overhead, doubly linked lists, and reference stability. Here you combine those ideas into a repeatable way to choose between an array and a linked# A practical framework for choosing
This chapter assumes you know basic Big-O notation, understand references or pointers, and have read the earlier chapters on memory layout, access cost, insertion and deletion, dynamic array growth, cache locality, memory overhead, doubly linked lists, and reference stability. Here you combine those pieces into a repeatable way to decide between an array (including a dynamic array) and a linked list.
Start from the workload, not the structure
Asymptotic costs only matter for the operations your program actually performs. Before choosing, write down the workload:
- Which operations dominate: indexed reads, scans, appends, inserts or removals in the middle, removals at the ends?
- How large does the collection get, and does its size vary a lot?
- Do other parts of the program hold long-lived references to elements?
- Is the code on a hot path, where constant factors matter?
If you cannot answer these, default to a dynamic array. It is the right choice more often than not, for reasons covered below.
The cost summary
| Operation | Dynamic array | Singly linked list | Doubly linked list |
|---|---|---|---|
| Access i-th element | O(1) | O(n) | O(n) |
| Search by value | O(n) | O(n) | O(n) |
| Append at end | Amortized O(1) | O(1) with a tail pointer | O(1) with a tail pointer |
| Insert at front | O(n) | O(1) | O(1) |
| Insert in middle, position given as index | O(n) | O(n) to find, then O(1) | O(n) to find, then O(1) |
| Insert after a node you hold | Not applicable | O(1) | O(1) |
| Remove a node you hold | Not applicable | O(n) to find predecessor | O(1) |
| Element addresses stay valid | No, resizing moves them | Yes | Yes |
The key qualifier appears twice in the table. Linked list insertion and removal are O(1) only when you already hold the relevant node. If you must search for it first, the search costs O(n), and the array's cheaper scan often cancels the linked list's advantage.
Decision flow
Checks that override Big-O
After a first pick from the flow, test it against the practical factors.
- Cache locality. Arrays store elements side by side, so scans use each cache line fully. Linked nodes can be scattered across memory, so each hop may be a cache miss. For small and medium collections, an array with O(n) shifting often beats a linked list with O(1) insertion.
- Memory overhead. Each linked node adds at least one reference, and a doubly linked node adds two, plus allocator bookkeeping. A dynamic array wastes at most the unused capacity.
- Reference stability. If other code stores pointers to elements, a resize invalidates them in languages with real pointers. Linked nodes never move. In Python, a list stores references to objects, so object identity is stable, but positions still shift.
- Allocation pattern. Many small node allocations cost more than one large buffer, and they fragment memory.
Worked example: an LRU cache
An LRU (least recently used) cache must look up an item by key, mark it as most recent, and evict the oldest item. Apply the framework:
- Lookup by key needs a hash map, which is separate from the sequence.
- "Mark as most recent" means moving an item to the front. With an array that shifts O(n) elements.
- The hash map can store a direct reference to each node, so the "do you hold the node" condition is met.
- Removing a node you hold is O(1) only in a doubly linked list.
The result is a hash map plus a doubly linked list, which is the standard design. Here is a compact version.
class DNode:
def __init__(self, key, value):
self.key = key
self.value = value
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.map = {}
self.head = DNode(None, None) # sentinel on the most recent side
self.tail = DNode(None, None) # sentinel on the least recent side
self.head.next = self.tail
self.tail.prev = self.head
def _unlink(self, node):
node.prev.next = node.next
node.next.prev = node.prev
def _push_front(self, node):
node.next = self.head.next
node.prev = self.head
self.head.next.prev = node
self.head.next = node
def get(self, key):
node = self.map.get(key)
if node is None:
return None
self._unlink(node)
self._push_front(node)
return node.value
def put(self, key, value):
node = self.map.get(key)
if node is not None:
node.value = value
self._unlink(node)
self._push_front(node)
return
if len(self.map) >= self.capacity:
oldest = self.tail.prev
self._unlink(oldest)
del self.map[oldest.key]
node = DNode(key, value)
self.map[key] = node
self._push_front(node)
cache = LRUCache(2)
cache.put("a", 1)
cache.put("b", 2)
cache.get("a")
cache.put("c", 3) # evicts "b"
print(cache.get("b")) # None
print(cache.get("a")) # 1The sentinel nodes remove special cases for empty lists and for the ends.
Common mistakes
- Choosing a linked list for a queue in a language whose standard library offers a deque, which is usually a better-tested structure for this purpose.
- Ignoring the cost of reaching the node, then claiming O(1).
- Optimizing before measuring. For collections under a few hundred elements, differences are often invisible.
- Forgetting that removing from a singly linked list needs the predecessor.
Exercise
A program keeps 50,000 sensor readings, appends new ones at the end, and mostly computes the average of the last 1,000 readings by scanning them. Which structure fits, and which two factors from this chapter justify it?
Show answer
A dynamic array. Appends are amortized O(1), and the scan over the last 1,000 elements benefits from cache locality because the elements are contiguous. Indexing from the end is also O(1), so finding where the window starts costs nothing, while a linked list would have to traverse to reach it and would add per-node memory overhead.
Exercise
In the LRU cache above, why does the design use a doubly linked list rather than a singly linked list?
Show answer
On every get, the cache must remove a node it already holds from the middle of the list. In a singly linked list, removal needs the predecessor, which requires an O(n) search. A doubly linked node has a prev reference, so unlinking is O(1).