Data Structures and Algorithms
The course every computer science major takes next, in Python: how to store data so the operations you need are fast, and how to count what an algorithm costs. Big-O, arrays and linked lists, stacks and queues, recursion and sorting, hash tables, trees and heaps, graphs, greedy and dynamic programming, each run step by step on a small case. Assumes you can write loops, functions and lists.
Lessons
- Counting steps: An algorithm's cost is the number of basic steps it takes as a function of the input size $n$, so one pass over $n$ items takes about $n$ steps and comparing every pair, a loop inside a loop, about $\frac{n^2}{2}$, and doubling $n$ doubles the first and quadruples the second.
- Big-O notation: Big-O keeps only how fast a step count grows, dropping constant factors and smaller terms, since $f(n)$ is $O(g(n))$ when $f(n) \le c\,g(n)$ for all large $n$; the common classes $1$, $\log n$, $n$, $n \log n$, $n^2$ and $2^n$ are worlds apart once $n$ is large.
- Best, worst and average case: One algorithm can take very different numbers of steps on inputs of the same size, as insertion sort makes $n - 1$ comparisons on a sorted list and $\frac{n(n-1)}{2}$ on a reversed one, so a running time says which case it means, and the worst case is the usual promise.
- Arrays and indexing: An array keeps its items side by side in one block of memory, so item $i$ sits at the start address plus $i$ times the item size and is reached in $O(1)$, but inserting or deleting near the front shifts every item after it, $O(n)$.
- Dynamic arrays and amortized cost: A dynamic array moves into a bigger block when it fills, classically one twice as big, so one append now and then copies everything, yet $n$ appends copy fewer than $2n$ items in all, which is $O(1)$ amortized per append.
- Linked lists: A linked list keeps each item in a node that points to the next, so adding or removing at the front, or just after a node already in hand, is $O(1)$ with nothing shifted, but reaching the $i$-th item means following $i$ links.
- Stacks: A stack adds and removes at one end only, last in first out, both $O(1)$ at the end of a Python list, which is exactly the order needed to match brackets, undo edits and run function calls.
- Queues and deques: A queue adds at the back and removes from the front, first in first out; a list's `pop(0)` shifts every item left, $O(n)$, so a queue wants both ends $O(1)$, which a deque or a circular buffer gives.
- Recursion and the call stack: A recursive function calls itself on a smaller case until it reaches a base case, and each call gets its own frame on the call stack with its own variables, so the answers are built as the calls return, and a missing base case fills the stack.
- Binary search: In a sorted array, one comparison with the middle item rules out half of what is left, so binary search keeps $lo$ and $hi$ around the only stretch where the target can be and finishes in about $\log_2 n$ steps.
- Merge sort: Merge sort sorts each half recursively and merges the two sorted halves in linear time; halving gives about $\log_2 n$ levels with $n$ work on each, $O(n \log n)$ in every case, at the price of $O(n)$ extra memory.
- Recurrences and recursion trees: A recursive algorithm's running time obeys a recurrence such as $T(n) = 2T(n/2) + n$, and adding up the work level by level in its recursion tree solves it, $n \log_2 n$ here, $\log_2 n$ for $T(n/2) + 1$ and about $\frac{n^2}{2}$ for $T(n-1) + n$.
- Quicksort: Quicksort partitions around a pivot, smaller items to its left and larger to its right, then sorts each side in place; even splits give $O(n \log n)$, but a pivot that is always the smallest, as the last item of a sorted list is, costs about $\frac{n^2}{2}$ comparisons, which a random pivot makes very unlikely.
- The limit on comparison sorting: A sort that learns only by comparing two items must tell all $n!$ orders apart, and a tree of yes-or-no questions with $n!$ leaves is at least $\log_2(n!) \approx n \log_2 n$ deep, so no comparison sort beats $O(n \log n)$ in the worst case; counting sort escapes by not comparing.
- Hash tables: A hash table turns a key into an array index with a hash function, so a lookup goes straight to one bucket instead of searching, which is why `x in s` for a set is $O(1)$ on average and for a list $O(n)$.
- Collisions and load factor: Different keys can land in the same bucket, so each bucket keeps a chain and a lookup searches only its own; the load factor $\alpha = n/m$ is the average chain length, and doubling the buckets when it passes a bound keeps lookups $O(1)$ expected, though the worst case is $O(n)$.
- What makes a good hash function: A hash function must give equal keys equal hashes, which is why a list that can change can't be a key, and a good one spreads different keys evenly over the buckets, where a weak one such as adding up letter codes piles every anagram into one chain.
- Binary trees and traversals: A binary tree is a root with a left and a right subtree, so tree code is naturally recursive, and preorder, inorder and postorder differ only in whether a node is handled before, between or after its two subtrees.
- Binary search trees: In a binary search tree every key in a node's left subtree is smaller and every key in its right subtree larger, so search and insert follow one path down from the root, $O(h)$ for height $h$, and an inorder walk lists the keys in sorted order.
- Deleting from a binary search tree: Removing a leaf or a node with one child only reconnects its parent, but a node with two children takes the key of its successor, the smallest key in its right subtree, which has no left child and so comes out easily.
- Balance and rotations: The same keys inserted in sorted order make a chain of height $n - 1$, so balanced trees such as AVL and red-black trees keep the height $O(\log n)$ by rotating, a change of three links that lifts a child over its parent and keeps the keys in order.
- Heaps and priority queues: A min-heap is a complete binary tree kept in an array, every parent no larger than its children, so the smallest item is at index $0$, node $i$'s children are at $2i + 1$ and $2i + 2$, and an insert sifts up one path, $O(\log n)$.
- Removing the minimum, and heap sort: Removing the minimum moves the last item to the root and sifts it down, swapping with the smaller child, in $O(\log n)$, so a priority queue serves the most urgent item fast and $n$ removals sort in $O(n \log n)$.
- Representing a graph: A graph of $V$ vertices and $E$ edges can be stored as adjacency lists in $O(V + E)$ space, or as an adjacency matrix in $O(V^2)$ that answers "is there an edge?" in $O(1)$, and sparse graphs, the common kind, want lists.
- Breadth-first search: Breadth-first search visits vertices from a queue, all those one edge away before any two away, so it finds the path with the fewest edges to every vertex, in $O(V + E)$.
- Depth-first search: Depth-first search follows one path as far as it can before backing up to try another, by recursion or with a stack, and visits everything reachable in $O(V + E)$; an edge back to a vertex still on the path means a cycle.
- Topological sort: The vertices of a directed graph with no cycles can be lined up so every edge points forward, by repeatedly taking out a vertex with no edges coming in, and when none is left to take while vertices remain, the graph has a cycle.
- Dijkstra's algorithm: With no negative weights, repeatedly settling the closest unsettled vertex and relaxing its edges gives the shortest distance to every vertex, in $O((V + E)\log V)$ with a heap, and a single negative edge can make it wrong.
- Minimum spanning trees: Kruskal's algorithm takes the edges from lightest to heaviest and keeps each one that joins two pieces not yet connected, which builds the cheapest set of edges connecting every vertex, because the lightest edge across any split is always safe.
- Union-find: A union-find structure keeps each group as a tree of parent pointers, so two items are in the same group when they reach the same root, and joining by size with path compression makes each operation nearly constant time.
- Greedy algorithms: A greedy algorithm commits to the choice that looks best now and never takes it back, which is right for scheduling meetings by earliest finish, as an exchange argument shows, and wrong for making $6$ from coins of $1$, $3$ and $4$.
- Memoization: When a recursion solves the same subproblems again and again, as Fibonacci does, storing each answer the first time it is found turns exponential time into one computation per distinct subproblem.
- Bottom-up tables: A dynamic program can instead fill a table from the smallest subproblems up, each entry from entries already filled by a recurrence, as the fewest coins for every amount from $0$ to the target, with no recursion at all.
- Longest common subsequence: The longest common subsequence of two strings fills a grid where each cell comes from the cell above, to the left or diagonally before it, in $O(mn)$, and walking back through the grid recovers the subsequence itself, which is how a diff finds what changed.