Sub topic 5
Inserting and Deleting: Where the Cost Really Is
This chapter assumes you know basic Big-O notation, can read Python, and understand that a variable can hold a reference to an object. It covers one question: what does it cost to insert or delete an element in an array and in a linked list?
Two costs, not one
Every insertion or deletion has two parts:
- Finding the position where the change happens.
- Making the change itself.
Arrays and linked lists differ most on part 2. Textbook tables often hide part 1, and that is where most mistakes come from.
Inserting into an array
An array stores elements in adjacent slots. To insert at index i, every element from i onward must move one slot to the right to make room.
items = [1, 3]
items.insert(1, 2) # O(n): later elements shift one slot right
print(items) # [1, 2, 3]The cost depends on where you insert:
- At the front, all n elements shift, so the cost is O(n).
- In the middle, about n/2 elements shift, which is still O(n).
- At the end, nothing shifts. A dynamic array does this in amortized O(1), which a later chapter explains.
Deletion is the mirror image. Removing an element at index i leaves a gap, so every later element shifts one slot left to close it.
Finding the position is cheap. If you know the index, you reach it in O(1).
Inserting into a linked list
A linked list stores each element in a node that holds a reference to the next node. To insert, you create a node and change two references. Nothing else moves.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def insert_after(node, value):
node.next = Node(value, node.next)
head = Node(1, Node(3))
insert_after(head, 2) # O(1): only two references changeThe new node points at the old successor, and the predecessor points at the new node. The work is the same whether the list has ten nodes or ten million.
The catch: you must already hold the node
The O(1) claim has a condition. insert_after is constant time only because it receives the preceding node. If you only know "insert at index 500", you must first walk 500 links from the head. That walk is O(n), and it dominates the cost.
The same applies to deletion. In a singly linked list, removing a node requires the node before it, so that its next can skip over the target. If you hold only the target, you must search from the head to find its predecessor.
A doubly linked list stores a prev reference as well, so a node you hold can remove itself:
class DNode:
def __init__(self, value):
self.value = value
self.prev = None
self.next = None
def unlink(node):
if node.prev is not None:
node.prev.next = node.next
if node.next is not None:
node.next.prev = node.prev
node.prev = None
node.next = NoneThis is O(1) given the node. If the node was the head or tail, the caller must also update the list's own head or tail reference, because unlink does not know about the list.
Comparing the totals
| Operation | Array (position known) | Singly linked list, node held | Singly linked list, only index known |
|---|---|---|---|
| Insert at front | O(n) | O(1) | O(1) |
| Insert in middle | O(n) | O(1) | O(n) to find, then O(1) |
| Insert at end | Amortized O(1) | O(1) with a tail pointer, otherwise O(n) | O(n) without a tail pointer |
| Delete in middle | O(n) | O(1) with predecessor | O(n) |
Insertion at the front of a linked list is O(1) because the head is always held. This makes the front the linked list's strongest position.
When the list actually wins
A linked list pays off when you keep references to nodes across operations. Examples include a cursor that moves through a list and edits as it goes, or a cache that stores a node handle for each key. In both cases, the position is found once and reused, so each edit is cheap.
If your workload is "find by value, then remove", both structures pay O(n) to find. The array then pays O(n) again to shift, but that shift is a fast block memory move. The two structures end up closer than the Big-O table suggests, and a later chapter on cache locality explains why.
Exercise
A singly linked list has 1,000 nodes and a tail pointer. You are given only the value 742 and must delete the node containing it. What is the cost, and why is it not O(1)?
Show answer
It is O(n). You must walk from the head to find the node, and also track its predecessor so you can relink around it. The O(1) deletion cost applies only when you already hold the predecessor node. The tail pointer does not help because the target is not at the end.
Exercise
You insert 10,000 items, one at a time, at the front of a Python list using items.insert(0, x). Roughly how many element moves occur in total, and which structure would avoid them?
Show answer
About n²/2, roughly 50 million moves, because the k-th insert shifts k elements. A singly linked list avoids this because inserting at the head is O(1) each time, for 10,000 operations in total.