Sub topic 13
Complexity of Common Data Structure Operations
This chapter assumes you can read Big O notation, know the common complexity classes, and understand best, worst, and average case. It also assumes you know what amortized cost means. The goal is a working table of operation costs for the structures you use daily, and an understanding of why each cost is what it is.
Why costs belong to operations, not structures
A data structure does not have one complexity. Each operation on it has its own cost, and that cost often depends on the case. A Python list has O(1) indexing and O(n) membership tests. A hash table has O(1) average lookup and O(n) worst-case lookup.
When you read a complexity table, ask three questions:
- Which operation is it?
- Is the figure worst case, average case, or amortized?
- What does n count? Usually it is the number of stored elements, but sometimes it is the key length or the size of another argument.
Arrays and dynamic arrays
An array stores elements in one contiguous block of memory. The address of element i is the start address plus i times the element size. That arithmetic takes constant time, so indexing is O(1).
Python's list is a dynamic array. It keeps spare capacity and grows by a factor when it fills up. A single resize copies every element, which costs O(n). The doubling simulation below counts the copies across many appends:
def count_copies(appends):
capacity, size, copies = 1, 0, 0
for _ in range(appends):
if size == capacity:
copies += size # resize: copy every existing element
capacity *= 2
size += 1
return copies
for n in (10, 1000, 100000):
print(n, count_copies(n)) # total copies stay below 2 * nThe total copy work stays below 2n, so append is O(1) amortized. The cost of any single append can still be O(n). That matters if you have a hard latency limit on each call.
Operations in the middle or at the front are costly. Inserting or deleting at index i shifts every later element, so it costs O(n). Removing the last element with pop() is O(1). Removing the first with pop(0) is O(n).
| Operation on a dynamic array | Cost |
|---|---|
| Index read or write | O(1) |
| Append | O(1) amortized, O(n) worst case |
| Pop from the end | O(1) |
| Insert or delete at index i | O(n) |
| Search by value (unsorted) | O(n) |
| Search by value (sorted, binary search) | O(log n) |
Linked lists
A singly linked list stores each element in a node that points to the next node. There is no address arithmetic, so reaching the element at index i means following i pointers. Access by index is O(n).
What you gain is cheap changes at a known position. If you already hold a reference to a node, inserting after it takes O(1), because you only rewire pointers. Inserting at the head is O(1). Inserting at the tail is O(1) only if you also keep a tail pointer.
The catch is the word "already". Finding the position is the O(n) part. A common error is to say "linked lists have O(1) insertion" and forget the search. For "insert at index i", an array and a linked list are both O(n). They differ in where the work goes: shifting elements in the array, walking nodes in the linked list.
| Operation on a singly linked list | Cost |
|---|---|
| Access by index | O(n) |
| Insert or delete at head | O(1) |
| Insert after a node you hold | O(1) |
| Delete a node you hold (singly linked) | O(n), since you need the previous node |
| Search by value | O(n) |
A doubly linked list stores a previous pointer too, so deleting a node you hold becomes O(1).
Stacks and queues
A stack supports push and pop at one end. A dynamic array gives O(1) amortized push and O(1) pop from the end, so list works well as a stack.
A queue adds at one end and removes at the other. Using a list with pop(0) makes each dequeue O(n). Use collections.deque, which supports O(1) appends and pops at both ends:
from collections import deque
queue = deque()
queue.append("a") # enqueue, O(1)
queue.append("b")
first = queue.popleft() # dequeue, O(1)
print(first) # adeque indexing in the middle is O(n), so it is not a drop-in replacement for list when you need random access.
Hash tables
A hash table (Python dict and set) computes a hash of the key, turns it into a slot number, and stores the entry there. Lookup, insert, and delete all follow the same path, so they share one cost profile.
- Average case: O(1), assuming the hash function spreads keys evenly and the table is kept from getting too full.
- Worst case: O(n), when many keys collide into the same slot and the table must scan them.
- Insert is also amortized, because the table resizes and rehashes all entries when it fills.
The average-case figure depends on assumptions. Poor hash functions, or adversarial keys chosen to collide, push the cost toward O(n). Python randomizes string hashing per process for this reason.
The "O(1)" also hides the cost of hashing the key itself. Hashing a string of length k takes O(k). For short keys this is negligible. For very long keys, n is not the only variable.
Hash tables give no useful ordering. Finding the minimum key or iterating in sorted order costs O(n) for the minimum and O(n log n) to sort.
Balanced binary search trees
A binary search tree (BST) keeps smaller keys in the left subtree and larger keys in the right. Search, insert, and delete each follow one path from the root downward, so the cost is O(h), where h is the height.
The height depends on shape:
- Balanced tree: h is about log2(n), so operations cost O(log n).
- Degenerate tree: inserting keys in sorted order into a plain BST produces a chain with h = n, so operations cost O(n).
Self-balancing trees such as AVL and red-black trees rotate nodes to keep h at O(log n) in the worst case. In exchange, they also keep keys in sorted order. That gives operations a hash table cannot offer cheaply: minimum, maximum, successor, and range queries.
| Operation | Hash table | Balanced BST |
|---|---|---|
| Search by key | O(1) average, O(n) worst | O(log n) |
| Insert | O(1) average, O(n) worst | O(log n) |
| Delete | O(1) average, O(n) worst | O(log n) |
| Minimum or maximum | O(n) | O(log n) |
| Iterate in sorted order | O(n log n) | O(n) |
Heaps
A binary heap stores a complete binary tree in an array, with each parent no larger than its children (a min-heap). The smallest element is always at index 0.
- Peek at the minimum: O(1).
- Push: O(log n). The new item is placed at the end and moved up at most h levels.
- Pop the minimum: O(log n). The last item replaces the root and moves down at most h levels.
- Search for an arbitrary value: O(n), because the heap only orders parents against children.
- Build a heap from n items: O(n) with
heapify, not O(n log n).
import heapq
items = [5, 3, 8, 1, 9, 2]
heapq.heapify(items) # O(n)
heapq.heappush(items, 0) # O(log n)
print(heapq.heappop(items)) # 0, O(log n)
print(items[0]) # 1, peek at the minimum in O(1)Choosing by the operations you need
The best structure depends on which operations dominate your workload. The flow below summarizes common decisions.
Common errors
- Treating
x in some_listas cheap. It is O(n). Inside a loop of n iterations it makes the whole loop O(n^2). Converting the list to asetfirst makes each test O(1) on average. - Using
list.pop(0)orlist.insert(0, x)in a loop. Each call is O(n). Usedeque. - Quoting average-case hash costs as guarantees. If an attacker controls the keys, or latency limits are strict, plan for the worst case.
- Forgetting hidden costs. Slicing
items[a:b]copiesb - aelements. String concatenation in a loop can cost O(n^2) overall, because each step copies the growing string. - Ignoring what n means. For a hash table keyed by long strings, cost scales with key length as well as the number of entries.
Putting it together: a worked comparison
Suppose you must check whether any value in a list a of n items also appears in a list b of n items.
def overlap_nested(a, b):
for x in a:
if x in b: # O(n) list scan inside an O(n) loop
return True
return False # O(n^2)
def overlap_set(a, b):
seen = set(b) # O(n) to build
for x in a:
if x in seen: # O(1) average
return True
return False # O(n) averageThe first version is O(n^2). The second is O(n) on average and spends O(n) extra space on the set. This is the usual trade: you buy lower time complexity with memory.
Exercise
You keep n items in a plain (unbalanced) binary search tree and insert them in already-sorted order. What is the cost of a single search afterward, and what change would guarantee O(log n)?
Show answer
Sorted insertion produces a chain of height n, so a search costs O(n). Using a self-balancing tree such as an AVL or red-black tree keeps the height at O(log n), so each search costs O(log n) in the worst case.
Exercise
A program processes a queue implemented as a Python list, calling pop(0) to take each of n items. What is the total time, and how do you fix it?
Show answer
Each pop(0) shifts the remaining elements, so it costs O(n), and n calls cost O(n^2) in total. Replace the list with collections.deque and call popleft(), which is O(1), for O(n) total.