1/102
Looks like no tags are added yet.
Time complexity
How runtime grows as input size n grows.
Space complexity
How memory use grows as input size n grows. Memory is often the real limit.
How do you find the order of growth of code?
Count the loops: how many times the innermost work runs as a function of n.
Single loop over n items
O(n). 10x the data is 10x the work (an if inside doesn't change the order).
Nested loops over n (both over len(data))
O(n^2) quadratic. 10x the data is 100x the work. The most common way code quietly stops scaling.
O(1)
Constant. Example: list index, dict lookup.
O(log n)
Logarithmic. Example: binary search, halving each step.
O(n)
Linear. Example: one pass over the data.
O(n log n)
Linearithmic. Example: a good general-purpose sort.
O(n^2)
Quadratic. Example: compare every pair.
O(2^n)
Exponential. Example: try every subset.
O(n!)
Factorial. Example: try every ordering (travelling salesman brute force).
Three Big-O simplification rules
(1) Drop constants (3n is O(n)). (2) Log base doesn't matter (differ by a constant). (3) Keep only the fastest-growing term (n^2 + 100n + 500 is O(n^2)).
Complexity of a triangular loop (for i in range(n): while j <= i)
1 + 2 + … + n = n(n+1)/2 iterations, so O(n^2).
Complexity of j = n; while j > 0: j = j // 2
O(log n). It halves each step, about log2(n) steps.
Best case vs worst case vs average case
Best = luckiest input (Omega). Worst = unluckiest input, usually quoted because it is the guarantee. Average = typical input.
Big-O vs Theta
Big-O is strictly an upper bound (an O(n) algorithm is also O(n^2)). Theta means growth is exactly that order (tight bound). In practice, O(…) is used to mean Theta, and the course does too.
How to measure scaling empirically
Time the code at several input sizes and plot time vs n on log-log axes. A power law t = c*n^k is a straight line with slope k (about 1 = linear, about 2 = quadratic). Fit with np.polyfit(np.log(sizes), np.log(times), 1)[0].
Effect of a constant factor on a log-log plot
Shifts the line up or down but does not change its slope.
Why is NumPy faster than a Python loop if both are O(n)?
Constant factors: NumPy runs compiled C over contiguous memory. Big-O gives the growth; the constant decides milliseconds vs minutes (why vectorizing matters).
Memory of an n x n float64 matrix
8 bytes x n^2. 1,000 rows is trivial, 50,000 rows is about 20 GB. Check this before an agent materializes all pairwise distances.
Amortized cost
Average cost per operation over many calls when an operation is usually cheap but occasionally expensive. Example: list.append is amortized O(1).
Performance budget
An acceptance criterion with a number, e.g. "full 7M-row file in under 5 s and 2 GB". Observable, so the agent can test it and report PASS/FAIL (unlike "make it faster").
Complexity of an agent session's token cost
Quadratic. The model has no memory so each turn resends the conversation; turn k sends about k turns of tokens, and 1+2+…+turns grows like turns^2. Compact or start fresh to control it; caching lowers price but not the shape.
Why are Python lists and NumPy arrays O(1) to index?
Contiguous memory: element k is at start + k * itemsize, a single address calculation.
Why is growing an array expensive?
The block has fixed size, so growing means allocating a bigger block and copying everything.
Python list over-allocation
Lists keep spare room at the end, so most appends are O(1) and only occasionally copy. Append is amortized O(1).
list.insert(0, x) cost
O(n). Every element shifts. 160,000 insert(0, i) calls are O(n^2).
np.append in a loop
Quietly O(n^2): NumPy arrays don't over-allocate, so each call copies the whole array. Fix: build a Python list, convert to an array once at the end.
pd.concat inside a loop
O(n^2), copies the whole result each time. Fix: collect chunks in a list and call pd.concat(chunks) once (O(n)).
Linked list
Each element is a node holding a reference to the next; the list is just a reference to the head. Nothing is contiguous.
Linked list: index item k
O(n). No address arithmetic, follow k references from the head.
Linked list: add at front
O(1). Make a new node point at the old head, no copying.
Linked list: add_back
O(n) walking to the end, but O(1) if you keep a tail reference. Removing from the back of a singly linked list is still O(n).
Array vs linked list trade-off
Array: O(1) index, O(n) front insert, low memory overhead. Linked list: O(n) index, O(1) front insert, higher overhead (a reference per node). In data science arrays usually win (scan/index more than splice, compiled loops).
Hash table (dict/set)
A hash function turns a key into a number that picks a bucket. Lookup, insert and membership are average O(1), independent of number of items.
Why is x in some_set O(1) but x in some_list O(n)?
A set hashes x and goes straight to its bucket; a list scans every element.
Hashable
A key that is (in practice) immutable, so its hash still points to the right bucket. Tuples work; lists, sets and DataFrames raise TypeError. Use a tuple like (zone, hour) for a compound key.
Hash collisions
Many collisions degrade lookups toward O(n), but Python's hashing makes this rare, so treat dict/set ops as O(1).
Quiet quadratic: membership test against a growing list in a loop
O(n^2); doubling the data roughly quadruples the time. Fix: use a set.
pandas Index is a …
A hash table. After set_index, .loc label lookup is O(1) vs an O(n) boolean scan (df.loc[df["id"] == k]).
What do groupby and merge use under the hood?
Hash tables: groupby hashes group keys to bucket rows; merge hashes join keys to find matches.
Many-to-many join blow-up
merge pairs every matching left row with every matching right row, so rows are the product of matches. Keys [1,1,2] merged with [1,1,2] give 5 rows (1: 2x2=4, 2: 1).
Guard against merge blow-up
pd.merge(…, validate="one_to_one" / "one_to_many" / "many_to_one") raises MergeError instead of silently exploding.
Hash join vs sort-merge join
Hash join: build hash table on one side, probe with other, about O(n + m). Sort-merge: sort both then walk together, about O(n log n + m log m); sort cost vanishes if already sorted.
Stack
LIFO (last in, first out). One access point (top): push, pop, peek. A Python list is already a stack (append, pop(), [-1], all O(1)).
Queue
FIFO (first in, first out). Two access points (front, rear): enqueue, dequeue. Used in autograders, print spoolers, schedulers.
Stack vs queue
Stack: LIFO, one access point, push/pop. Queue: FIFO, two access points, enqueue/dequeue.
Push 10, 20, 30, 0, -30 then pop five times
-30, 0, 30, 20, 10 (a stack reverses order).
Stack use cases
Undo (push each edit, pop the latest) and bracket matching (stack holds unclosed openers; a closer must match the top; leftovers mean unbalanced).
Why is a list a bad queue?
pop(0) is O(n) because every remaining element shifts, so draining is O(n^2). Use collections.deque (O(1) at both ends, popleft()).
Call stack
Each function call pushes a frame (local variables and return location); returning pops it.
Traceback
A printout of the call stack when something went wrong. Read it bottom-up: the last line is the actual error, frames above are the chain of calls.
Recursion
A function calls itself on a smaller version of the problem until a base case it can answer directly.
Python recursion limit
About 1000 frames (sys.getrecursionlimit()); exceeding raises RecursionError. A correct function fails if the depth is too large. Python does not do tail-call optimization.
When to use recursion vs a loop
Recursion for shallow, tree-shaped problems (depth about log n); a loop when depth could grow with the data. Any recursion can be a loop plus a stack you keep yourself.
Flood fill without RecursionError
Use an explicit stack (DFS) or deque (BFS) in a loop, or call scipy.ndimage.label. Recursive version fails because the pending-call chain is thousands deep.
Binary tree
A tree where each node has up to two children.
BST property
For every node, everything in its left subtree is smaller and everything in its right subtree is larger (the whole subtree, not just the immediate child).
BST search cost
The height of the tree. Balanced: O(log n) best; degenerate: O(n) worst. Lecture quiz answer: O(log n) best, O(n) worst.
BST degeneracy
Inserting already-sorted values always goes right, so the tree becomes a line (a linked list in disguise) with height n and O(n) search. Shape depends on insertion order.
Self-balancing trees
Red-black and AVL trees rearrange on insert to keep height O(log n) regardless of insertion order.
B-tree
A shallow, wide balanced tree used by databases and join indexes, tuned so each step reads one disk/memory block. Lookups stay O(log n) whatever the order of arrival.
In-order traversal
Left, node, right. Visits a BST in sorted ascending order. Recursion is fine since depth is about log n.
Pre-order and post-order traversal
Pre-order (node, left, right): used to serialize a tree. Post-order (left, right, node): used to free a tree bottom-up.
Removing a node from a BST
Leaf: detach it. One child: replace node with its child. Two children: replace value with its in-order successor (smallest in right subtree), then remove the successor.
Binary search on a sorted array
Look at the middle; each comparison keeps one half. O(log n), just indices, no pointers. Python: bisect.bisect_left(arr, x). 500,000 items in about 19 steps.
kd-tree
Binary search in space: cycles through dimensions (x, then y, then x…) splitting space so nearest-neighbor search is about O(log n) on average vs scanning all n. scipy.spatial.KDTree: build once, then query.
Great-circle distance trap for kd-trees
A kd-tree uses whatever distance you give it. Flat lat/lon treats longitude +179.5 and -179.5 as 359 degrees apart (dateline) and breaks near poles. Use great-circle distance or project coordinates first.
Heap
A complete binary tree with the heap property. Min-heap: every parent is less than or equal to its children, so the smallest is at the root. Insert and remove-min are O(log n).
Heap insert and remove-min
Insert: put at end, bubble up past larger parent. Remove-min: take root, move last item to root, bubble down past smaller child. Each moves along one root-to-leaf path, O(log n).
Heap array indices
Node i has children at 2i+1 and 2i+2; parent of i is (i-1)//2. Python heapq works on an ordinary list; h[0] is the minimum (array is not fully sorted).
Is [1, 3, 2, 7, 4, 5] a valid min-heap? [1, 2, 5, 3, 4, 0]? [3, 1, 2]?
Only the first is valid. The second has 5 (index 2) with child 0 (index 5). The third has a root larger than its children.
Top-k with a heap
Keep a size-k heap of the best seen: O(n log k) vs O(n log n) for a full sort. heapq.nlargest / nsmallest.
Selection sort
Best O(n^2), worst O(n^2), extra space O(1), not stable. Repeatedly find smallest of the rest and swap into place.
Insertion sort
Best O(n) (nearly sorted), worst O(n^2), extra space O(1), stable. Grows a sorted prefix.
Merge sort
Best and worst O(n log n), extra space O(n), stable. Split in half, sort each, merge. About log n levels with O(n) merging each.
Quick sort
Best O(n log n), worst O(n^2), extra space O(log n), not stable. Partition around a pivot and recurse. Usually fastest in practice.
Heap sort
Best and worst O(n log n), extra space O(1), not stable. Build a heap, pop min n times.
Why can't a comparison sort beat O(n log n)?
It must distinguish n! orderings, each comparison halves the possibilities, so it needs about log2(n!) which is roughly n log n comparisons.
Counting sort and radix sort
Reach O(n) by not comparing (reading digits or buckets), so they only apply to certain kinds of keys.
Stable sort
Equal elements keep their original order. Needed for multi-key sorts (sort by name, then stable sort by city) and reproducible rankings.
Which sort do Python, NumPy and pandas use?
Python sorted/list.sort: Timsort (merge + insertion, stable). NumPy np.sort: introsort (quicksort falling back to heapsort), not stable unless kind="stable". pandas sort_values: NumPy underneath, default quicksort, use kind="stable".
Why can a top-10 table change between runs?
Ties have no guaranteed order under the default unstable quicksort. Use kind="stable" or an explicit tie-breaker like sort_values(["trips", "pulocationid", "dolocationid"]).
Sorting inside a loop anti-pattern
Re-sorting a growing list on every add turns O(n log n) into O(n^2 log n). Use a heap if you need the largest few, or sort once at the end.
External (out-of-core) merge sort
Sort chunks that fit into sorted runs on disk, then stream-merge the runs in one pass with a heap of size = number of runs (heapq.merge). Used by databases and Unix sort.
Graph
Vertices connected by edges. Models road networks, social links, citations, pipeline dependencies. Edges can be undirected or directed. A tree is a graph with no cycles and a root.
Adjacency list
Maps each vertex to a list of neighbors. Space O(|V| + |E|); edge lookup by scanning neighbors. Best for sparse graphs (scipy.sparse does this).
Adjacency matrix
n x n grid. Space always O(n^2); edge lookup O(1). A 1M-vertex sparse graph would need 10^12 entries, almost all zeros.
DFS vs BFS
DFS (depth-first) uses a stack and goes as deep as possible before backtracking. BFS (breadth-first) uses a queue (deque.popleft()) and explores in rings. Same algorithm, different structure holding vertices to visit. Both O(|V| + |E|).
BFS shortest paths
BFS reaches each vertex first via the fewest edges, so it gives shortest paths in an unweighted graph (track a dist dict).
Dijkstra's algorithm
Shortest paths in a weighted graph: like BFS but always pulls the closest unvisited vertex next using a priority queue (heap), O(log n) per step. Use scipy.sparse.csgraph or networkx.
DAG (directed acyclic graph)
Directed graph with no cycles. A dependency is a directed edge. Pipelines, make, package install plans, spreadsheet references, Airflow and Dask are DAGs.
Topological sort
Orders vertices so every edge points forward (every task after its dependencies). That order is the execution plan, found in O(|V| + |E|). graphlib.TopologicalSorter(pipeline).static_order().
What does a topological sort failure mean?
There is a cycle (circular dependency), so no valid order exists. graphlib raises CycleError instead of looping forever.
Intractable problems
No known efficient algorithm as they grow (e.g. travelling salesman, O(n!) brute force; 20 cities about 6e16 routes). Real tools return a heuristic, so "optimal" often means "a sensible heuristic".
Agent pattern: prompt chaining
One agent's output feeds the next. Graph shape: a path (linear DAG).
Agent pattern: routing
A classifier sends work down one branch. Graph shape: a tree.
Agent pattern: parallelization
Split, run at once, combine. Graph shape: fan-out and fan-in (DAG).
Agent pattern: orchestrator-workers
A lead agent hands pieces to workers and merges results. Graph shape: a tree.