Skip to content

Data structures and Big-O in practice

Phase 1 · Working like an engineer · 15 min read

What you'll be able to do

  • Estimate how an algorithm's work grows before a dataset makes a slow choice painful.
  • Choose Python containers for lookup, ordering, queues, and top-k work.
  • Spot accidental quadratic loops and measure whether a change actually helps.

Cost grows with input size

Let n be the number of records. Big-O describes how work grows as n grows; it does not give seconds. Count the dominant operations and ignore constant multipliers for the growth label. The table uses log2(n) and rounded operation units, not measured runtimes.

Growth n = 10 n = 1,000 n = 1,000,000
O(1) 1 1 1
O(log n) 3.3 10 20
O(n) 10 1,000 1,000,000
O(n log n) 33 10,000 20,000,000
O(n²) 100 1,000,000 1,000,000,000,000

For example, at a million records, n log2(n) is about 1,000,000 × 20 = 20,000,000; n² is a trillion. A linear scan repeated for every item is quadratic. A worst-case bound covers the hardest input of a given size; an average-case bound assumes an input distribution. State which you mean. Constants, locality, and CPU caches can make a linear scan faster than a hash lookup for small n; the growth gap dominates eventually.

Some operations are amortized: one Python list append may occasionally copy the backing storage as it grows, but many appends together cost O(n), or amortized O(1) each. That is different from claiming every append takes constant time.

Pick the container for the operation

Need Python tool Typical cost
Read item at position i list[i] O(1)
Check membership in a list x in items O(n)
Append / insert at front list.append / list.insert(0, x) Amortized O(1) / O(n)
Lookup or membership dict / set Average O(1)
Add or remove at either end collections.deque O(1)
Find smallest pending item heapq O(1) peek; O(log n) push/pop

Lists are excellent for indexed sequences. A set answers “have I seen this?” without scanning old items; a dict adds a value to each key. This turns a common quadratic loop into linear expected work:

seen = set()
unique = []
for item in items:
    if item not in seen:
        seen.add(item)
        unique.append(item)

Use a deque for a first-in, first-out queue: removing the front of a list shifts the remaining elements. A list works well as a last-in, first-out stack with append and pop. Breadth-first search and schedulers use queues; depth-first search and undo histories naturally use stacks.

Why hashing works, and when it does not

A hash function turns a key into an integer. A hash table uses a key's hash to choose where to start looking. If another key occupies that position, it checks equality and searches another position; implementations differ in how they resolve collisions. Two keys landing together is a collision, not data loss. A fuller table has a higher load factor and more collisions. A table periodically resizes and redistributes entries, trading extra memory and occasional copying for average O(1) lookup. A pathological collision pattern can make lookup O(n).

Keys must be hashable: their hash and equality behavior must remain stable while stored. A tuple whose elements are all hashable works; a list does not. Mutating a key after insertion could put it in the wrong bucket, so Python rejects common mutable containers as keys. Python dicts iterate in insertion order, which is not sorted key order. For a longer treatment, see Software Engineering Handbook, chapter 3, “Cấu trúc dữ liệu & Big-O.”

Keep order only when it pays

On a sorted list, binary search halves the remaining range each step: about 20 comparisons for a million entries. bisect finds a position in O(log n), but inserting there into a Python list still shifts elements and costs O(n). sorted(items, key=...) costs O(n log n) in the general case. It is stable: items whose keys compare equal keep their original relative order, which makes multi-stage sorting predictable.

A heap maintains only enough order to expose its smallest item. Keep a heap of the best k candidates: each of n candidates may trigger an O(log k) update, for O(n log k) time and O(k) extra space. Sorting everything costs O(n log n) and usually stores all candidates. When k = 20 and n = 1,000,000, log2(k) is about 4.3 versus log2(n) about 20; actual speed still needs measurement.

Trees support ordered search without shifting a whole array on each insertion. Database B-trees use wide nodes, keeping the tree shallow and reducing costly storage reads. An index speeds lookups by maintaining such extra structure, at the cost of memory or disk space and work on writes. See Indexes and query plans for database behavior.

Dependencies are graphs

An adjacency list stores each node's neighbors, for example {"train": ["evaluate"]}. Breadth-first search (BFS) explores one distance layer at a time with a queue; depth-first search (DFS) follows a branch with a stack or recursion. Both take O(V + E) time when each node and edge is processed once.

A pipeline's tasks and dependency edges form a directed graph. If it has no directed cycle, it is a DAG. A topological order places every prerequisite before the task that needs it. You can repeatedly run tasks with zero unmet prerequisites, updating their dependents. If tasks remain but none is ready, there is a cycle; no valid execution order exists. See Data and ML pipelines.

Trade space for time, then measure

Remembering previous answers avoids repeated work. functools.lru_cache memoizes function results; a precomputed set, count table, or database index does something similar for lookups. The cost is stored entries, invalidation when inputs change, and sometimes slower writes. A streaming one-pass count can use space proportional to the number of distinct keys instead of loading every row; for unsorted input processed in one pass, exact deduplication generally needs a set of seen keys or external storage. If input is sorted by key, comparing adjacent keys needs O(1) working memory.

Measure a representative workload with timeit, then double input size. If time roughly doubles each time, growth looks linear; if it roughly quadruples, look for quadratic work. This tiny experiment measures one operation repeatedly:

import timeit

for n in (1_000, 2_000, 4_000):
    data = list(range(n))
    seconds = timeit.timeit(lambda: -1 in data, number=100)
    print(n, seconds)

The 100 repetitions reduce timer noise; divide by 100 for approximate time per lookup. To turn many timings into one number, define the exponent p: time is roughly proportional to n**p, so log(time) = constant + p * log(n). With x = log(size) and y = log(time), estimate p as sum((x - mean(x)) * (y - mean(y))) / sum((x - mean(x))**2). Sizes and times must be positive, and at least two sizes must differ. Micro-benchmarks can mislead, so profile the whole workload before redesigning it. Watch for x in a_list inside a loop, nested scans, sorting inside a loop, and expensive per-row callbacks repeated across a table. Repeated string concatenation can copy an ever-growing prefix, producing quadratic total copying; collect pieces and use ''.join(parts). Batch or precompute when repeated work is the bottleneck.

For AI engineers

For AI engineers

A training script that deduplicates 100 million rows cannot casually keep every row in a list and scan it for repeats. A set gives expected linear membership work but may exhaust RAM; external sorting or partitioned processing trades more I/O for bounded memory. A tokenizer's vocabulary lookup is naturally a dict, and collections.Counter counts n-grams. A retrieval service can keep its top k scores in a heap instead of sorting every match. Brute-force nearest-neighbor search compares a query with every vector, O(n) per query; approximate indexes trade exactness, build work, and memory for faster queries. See Choosing a datastore and Designing a RAG system. Bucketing examples by length can reduce wasted padding.

Common mistakes

  • Optimizing a function before measuring where end-to-end time goes.
  • Using a list as a set, then checking membership inside a loop.
  • Sorting the full collection again on each iteration instead of once.
  • Reading O(1) as “instant”; hashing, allocation, and cache misses still cost time.
  • Ignoring the memory growth of sets, indexes, heaps, and memoized results.
  • Choosing a clever structure whose maintenance cost and complexity do not fit the workload.

Check yourself

A loop tests each of one million IDs against a growing list of prior IDs. What growth should you expect, and what changes it?

Each membership test scans up to O(n) prior IDs, repeated n times: O(n²). Use a set of seen IDs for average O(1) membership and expected O(n) total work, with O(n) extra space.

You use bisect to find where a value belongs in a sorted Python list. Is insertion now O(log n)?

No. Finding the position is O(log n); shifting later elements to make room is O(n). The insertion remains O(n).

A pipeline task depends on itself through two other tasks. What should a topological scheduler do?

Report a cycle. No ordering can put all three prerequisites before the tasks that require them.

Timings for sizes 1,000, 2,000, and 4,000 are roughly 1, 4, and 16 ms. What do you investigate?

Quadratic growth is plausible because doubling size quadrupled time twice. Inspect nested scans and repeated list membership, then measure on representative inputs to confirm.

Lab

Work through six tasks (seven functions) in code/complexity-data-structures/. Preserve order while deduplicating, find the largest k items, and solve two-sum with hash lookups. Find the first unique item, order dependent tasks, and detect a dependency cycle. Run a doubling experiment and estimate its growth exponent from timings. Read README.md there for exact contracts; edit starter/lab.py. Run cd code/complexity-data-structures && PYTHONPATH=starter python -m pytest tests -q.

Go deeper