Complexity: Advanced
A Python list keeps its items in 1 contiguous block of memory slots, usually with a few spare slots at the end. When append finds every slot taken, the list cannot grow where it sits: it allocates a larger block, copies every existing reference into it, and frees the old one. That call costs O(n). Building a 10-million-row list with append in a loop still takes linear total time, and the reason is the size of the new block.
Charging each append in advance
slots = [None]size = 0copies = 0for item in ["a", "b", "c", "d", "e", "f"]:if size == len(slots):bigger = [None] * (len(slots) * 2)for i in range(size):bigger[i] = slots[i]copies += 1slots = biggerprint("resized to", len(slots), "slots, copies so far:", copies)slots[size] = itemsize += 1print(slots)print("appends:", size, "copies:", copies)
Each resize copies every stored item; appends between resizes write 1 slot.
The growth rule decides the total
CPython's own list_resize in Objects/listobject.c grows a full list by about one eighth of its size plus a few slots. That smaller factor copies each item about 8 times over a long run in exchange for less idle memory, and because growth is still proportional to size, append stays amortized O(1).
Where the guarantee stops
- Amortized differs from average caseAn average-case bound assumes some mix of inputs, and a bad input breaks it. An amortized bound holds for every sequence of appends.
- A single append can still stallThe resize on a 50-million-item list copies 50 million references before returning. Code with a per-request time limit feels that spike.
- Only the end of the list is cheapinsert(0, x) and pop(0) shift every item on every call, so n of them cost O(n²). A collections.deque handles both ends in O(1).
- A known size skips resizing[None] * n allocates the full block once, and filling it by index never resizes.
A loop runs once for each of the n rows in rows. Which loop body makes the whole loop O(n²)?
Split, solve, combine
def merge_sort(rows):if len(rows) <= 1:return rowsmid = len(rows) // 2left = merge_sort(rows[:mid])right = merge_sort(rows[mid:])merged = []i = j = 0while i < len(left) and j < len(right):if left[i] <= right[j]:merged.append(left[i])i += 1else:merged.append(right[j])j += 1merged += left[i:] + right[j:]print("merged", merged)return mergedprint(merge_sort([7, 3, 9, 1, 4]))
Each printed line is 1 combine step; the smallest merges finish first.
Reading the cost off the recursion
| Pattern | Parts per call | Combine step | Total |
|---|---|---|---|
| Binary search | 1 half | O(1) | O(log n) |
| Max of a range by halves | 2 halves | O(1) | O(n) |
| Merge sort | 2 halves | O(n) | O(n log n) |
| Peel off 1 item, recurse on the rest | 1 part of size n - 1 | O(n) | O(n²) |
The last row is the trap: peeling off 1 item per call gives n levels instead of log n. Sorting data bigger than memory reuses the merge step: sort chunks that fit, then stream the sorted runs through heapq.merge at O(log k) per row for k runs.
What is the time complexity of peak(values, 0, len(values)) on a list of n values?
Greedy: commit and never look back
Sorting by start time grabs backfill first, which holds the slot from hour 1 to hour 9 and blocks every other job. Sorting by end time is provably optimal: the job that finishes first leaves the most room afterward, and any best schedule can swap its first job for that one without losing a job. Repeating that swap down the schedule is an exchange argument, the usual proof behind a greedy rule. Cost: O(n log n) to sort plus 1 O(n) pass.
When the locally best choice is wrong
What a shuffle does
Input arrives split into partitions, each on a worker, in whatever order it was written. Grouping by user_id needs every row for a user on the same worker, so the engine computes a target worker from each key and sends the row there. That redistribution is a shuffle. Below, partition i starts on worker i, and the target is user_id % 3.
partitions = [[(101, 5), (102, 3), (101, 2)],[(103, 6), (101, 4), (102, 1)]]workers = {0: [], 1: [], 2: []}moved = 0for source, rows in enumerate(partitions):for user_id, amount in rows:target = user_id % 3workers[target].append((user_id, amount))if target != source:moved += 1for target, rows in workers.items():totals = {}for user_id, amount in rows:totals[user_id] = totals.get(user_id, 0) + amountprint("worker", target, totals)print("rows that crossed the network:", moved)
Every row for a user ends on 1 worker; rows whose target differs from their source cross the network.
Shrink the data before the shuffle
Only the partial rows travel through the shuffle; raw events never leave their worker.
Broadcast the small side of a join
| Plan | Rows moved | Total |
|---|---|---|
| Shuffle both sides | 500,000,000 + 250 | 500,000,250 |
| Broadcast countries | 250 × 100 workers | 25,000 |
A join pairs 2,000,000,000 events with 40,000,000 user rows on 400 workers. Which plan moves fewer rows?
Skew: 1 key, 1 slow worker
- ▸Each group-by or join on a new key shuffles the rows that reach it.
- ▸Steps that follow on the same key reuse the existing partitioning and add no shuffle.
- ▸Filters and dropped columns before a shuffle shrink every row that would cross.
Spotting them in pipeline work
| Pipeline task | Known hard problem |
|---|---|
| Pack files into the fewest 256 MB blocks without splitting any | Bin packing |
| Spread tasks across workers so the last one finishes soonest | Multiprocessor scheduling |
| Pick which summary tables to precompute within a storage budget | Knapsack |
| Choose the fewest source systems that together supply every needed column | Set cover |
| Group jobs into the fewest time windows so no 2 jobs writing the same table share one | Graph coloring |
- ▸Each item goes into 1 of k groups, and the groups have limits.
- ▸You choose a subset under a budget, and the items interact.
- ▸The answer is an ordering whose cost depends on which items sit side by side, as in routes. Sorting differs: each item's place follows from its own key.
- ▸Checking a proposed answer is fast, but finding one seems to need trying combinations.
Exact on tiny inputs, a heuristic at scale
Longest processing time first (LPT) is a greedy heuristic: sort the files largest first and hand each to the least-loaded worker, kept at the top of a heap. The program compares it with exhaustive search on 7 files and 3 workers.
Knowing how close you are
- Use a greedy rule with a proven bound: first-fit decreasing packing never uses more than 11/9 of the optimal bin count plus 1.
- Search exactly while n is small, cutting any branch that already exceeds the best answer found.
- Exploit small integers: when sizes and budget are whole numbers, memoized search runs in time proportional to items × budget. That is polynomial in the budget's value but exponential in its digit count, so a budget of 10,000 is fine and one in the trillions is out of reach.
- Improve and stop: start from greedy, move 1 item between workers, keep moves that lower the maximum, and halt at a time limit.
Which of these pipeline tasks is NP-hard?
The interpreter's constant factor
Python executes a loop body 1 bytecode instruction at a time. Built-ins such as sum, sorted, str.join and set operations run their loops in C. Two functions with the same O(n) growth can differ several times in speed:
Run it on your machine: the built-in typically finishes several times sooner. The seconds vary between machines; the ratio is what carries over. The same effect lets an O(n log n) sorted call in C beat an O(n) pure-Python loop at the sizes your pipeline sees, so measure before swapping one for the other.
Memory layout and the cache
A CPU fetches memory in cache lines, commonly 64 bytes on x86 processors, so reading neighbouring values is cheap and jumping around is expensive. One line of contiguous 8-byte numbers delivers 8 usable values. One line of a Python list delivers 8 pointers, and each int they point to is a separate object elsewhere in memory, often a fetch of its own. Contiguous storage pays off when C code walks the buffer: a columnar file reader decoding a whole column, or a numeric routine that takes the buffer directly. Iterating an array.array from Python gains nothing, because every element read builds a new int object, so a Python loop or sum over it runs no faster than over a list and often slower. Columnar file formats keep each column contiguous for the same reason: a query that reads 3 of 40 columns fetches only those 3, in order.
Storage: when a full scan beats an index
Choosing in practice
- Time both candidates with timeit at your real n before rewriting
- Push hot loops into built-ins: sum, sorted, set operations, str.join
- Read only the columns you need, in sequential order
- Recompute crossovers when hardware or data volume changes
- Pick an algorithm from Big-O alone when n is a few hundred
- Use an index for a query that matches a large share of rows
- Hand-write a Python loop to beat a C built-in of the same order
- Trust a single timing run; repeat it and compare the fastest
In this section's model, faster storage drops the random read cost from 50 units to 5, and the scan still costs 10,000. A query matches 1,500 rows. Which plan wins?
> A ride-sharing company's nightly job totals fares per driver across 2 billion trip rows on 400 workers, joins the 3 million per-driver totals to a 2,000-row city table, and writes the result as files for the payments team before morning.
Why appends stay cheap, shuffles stay costly, and some problems only ever get good-enough answers.
- Category
- Python
- Difficulty
- advanced
- Duration
- 26 minutes
- Challenges
- 16 hands-on challenges
Topics covered: Amortized Analysis, Divide-and-Conquer and Greedy, Complexity in Distributed Systems, When Problems Are Inherently Hard, When Theory Meets Reality
Lesson Sections
- Amortized Analysis
Charging each append in advance Picture an array that doubles its capacity whenever it fills. Starting from 1 slot, 6 appends trigger resizes at the 2nd, 3rd and 5th append, and each resize copies only the items already stored. Amortized analysis bounds the total cost of a whole sequence of operations, then divides by the number of operations. Charge every append 3 units: 1 pays for writing its own slot and 2 go into savings. When an array of capacity 2k fills up, the k items appended since the
- Divide-and-Conquer and Greedy
Two design patterns sit behind many of the fast algorithms you already use. Divide and conquer splits the input, solves each part recursively and combines the answers. Greedy takes the choice that looks best right now, commits to it and never revisits it. You can read each one's cost off its structure, but greedy carries a risk that divide and conquer avoids: a fast answer that is wrong. Split, solve, combine Merge sort is the standard case. A list of 1 item is already sorted, and 2 sorted lists
- Complexity in Distributed Systems
On a cluster, the step that dominates is moving a row between machines: the row is serialized, sent over the network, often spilled to disk, and read back. Two plans with the same O(n) CPU work can move very different numbers of rows, and that row count is the cost to minimize. What a shuffle does Four of the 6 rows crossed the network. With W workers and evenly spread keys, a row's target is its current worker only 1 time in W, so about (W - 1)/W of all rows move: two thirds on 3 workers, 99% o
- When Problems Are Inherently Hard
The intermediate tier showed a search over every combination doubling its work with each added item. For the family of problems called NP-hard, nobody has found an algorithm that runs in polynomial time, O(n^k) for some fixed k, in the worst case. They stand or fall together: a polynomial-time algorithm for any of the problems in this section would give one for all of them, and decades of searching have produced none. When a data task turns out to be one in disguise, stop hunting for a fast exac
- When Theory Meets Reality
Big-O describes how cost grows and drops constant factors. On real hardware a constant can be 50, and n is a number you can look up. The fastest approach comes from combining the growth rate with 3 practical costs: the interpreter, memory layout, and storage access. The interpreter's constant factor Memory layout and the cache Storage: when a full scan beats an index An index finds 1 row in O(log n), which sounds unbeatable next to an O(n) scan. A query matching many rows changes that: each matc