Sub topic 13
Complexity of Common Data Structure Operations
This chapter assumes you can read Big O notation, know the difference between worst-case, average-case, and amortized cost, and use Python lists, dicts, and sets.
Why the structure sets the cost
An algorithm's cost depends on the operations it performs and on how much each operation costs. Each data structure lays out its data in memory differently, so it makes some operations cheap and others expensive. Choosing a structure is often the same as choosing a complexity class.
The cost table
| Structure | Lookup or search | Insert | Delete |
|---|---|---|---|
| Dynamic array (Python `list`) | O(1) by index, O(n) by value | O(1) amortized at the end, O(n) elsewhere | O(1) at the end, O(n) elsewhere |
| Singly linked list | O(n) | O(1) at the head | O(1) at the head, O(n) to find a value |
| Hash table (`dict`, `set`) | O(1) average, O(n) worst | O(1) average | O(1) average |
| Sorted array | O(log n) with binary search | O(n) | O(n) |
| Balanced binary search tree | O(log n) | O(log n) | O(log n) |
| Binary heap | O(1) to read the minimum, O(n) to search | O(log n) | O(log n) to remove the minimum |
Where the costs come from
- Array index lookup is O(1). The address of element
iis the start address plusitimes the element size. No scanning is needed. - Inserting in the middle of an array is O(n). Every later element shifts one slot.
list.insert(0, x)is the worst case because it shifts all n elements. - Appending is O(1) amortized. The array doubles its capacity when it is full. An occasional O(n) resize is spread over many cheap appends.
- A linked list reaches any element only by following links. Finding the k-th node costs O(k). Insertion is O(1) only when you already hold a reference to the neighboring node.
- A hash table computes a bucket from the key. With a good hash function, buckets stay short, so operations average O(1). If many keys collide in one bucket, an operation degrades toward O(n).
- Trees and heaps are O(log n) because their height is about log n. This holds only if the tree stays balanced. An unbalanced binary search tree built from sorted input becomes a chain with O(n) operations.
Seeing the difference
This script times a membership test on a list and on a set. Exact times vary by machine. What matters is how they change as n grows.
from timeit import timeit
for n in (1_000, 100_000):
items_list = list(range(n))
items_set = set(items_list)
target = n - 1 # worst case for the list: last element
t_list = timeit(lambda: target in items_list, number=200)
t_set = timeit(lambda: target in items_set, number=200)
print(f"n={n}: list {t_list:.5f}s, set {t_set:.5f}s")The list time grows roughly 100 times when n grows 100 times, which is O(n). The set time stays almost flat, which is O(1) average.
Choosing a structure
Common errors
- Using
x in some_listinside a loop. Each test is O(n), so the loop is O(n^2). Convert the list to a set once, which costs O(n), then test in O(1). - Using
list.pop(0)as a queue. Each call shifts all remaining elements. Usecollections.deque, wherepopleft()is O(1). - Forgetting that slicing copies.
items[1:]costs O(n), so recursing onitems[1:]adds hidden linear work per call. - Quoting the average case as a guarantee. Hash table O(1) is an average. Adversarial or poorly hashed keys can reach O(n).
Exercise
A function receives a list a of n integers and a list b of n integers. It returns the values of b that also appear in a, using [x for x in b if x in a]. What is its time complexity, and how can you improve it?
Show answer
Each x in a test scans the list, which is O(n), and it runs for n values of b, so the total is O(n^2). Build set_a = set(a) once in O(n), then use [x for x in b if x in set_a]. Each test is O(1) on average, so the total is O(n) on average.