Section 5 · Revision
Algorithms formula sheet
Recurrences, complexities, standard counts and exam rules for every Algorithms topic on one page.
Asymptotic complexity
| Notation | Meaning |
|---|---|
| for all | |
| for all | |
| both of the above | |
Growth order: .
- Compare two functions by comparing their logs: , .
- . . , .
- . .
- does NOT follow from .
Master theorem for , with :
| Case | Condition | Result |
|---|---|---|
| 1 | ||
| 2 | , | |
| 2, | ||
| 2, | ||
| 3 | and , |
Other recurrences:
| Recurrence | Solution |
|---|---|
| (fractions sum below 1) | |
- recurrences: substitute , then .
Loop counting:
| Loop | Iterations |
|---|---|
i = 1; i <= n; i *= 2 |
|
i = 2; i <= n; i = i*i |
|
inner j = 1; j <= i with outer i *= 2 |
total, |
inner j += i for i = 1..n |
|
inner j *= 2 up to , outer i = 1..n |
Searching and sorting
| Algorithm | Best | Average | Worst | Space | Stable | In place |
|---|---|---|---|---|---|---|
| Bubble (early exit) | yes | yes | ||||
| Insertion | yes | yes | ||||
| Selection | no | yes | ||||
| Merge | yes | no | ||||
| Quick | to | no | yes | |||
| Heap | no | yes | ||||
| Counting | yes | no | ||||
| Radix ( digits, base ) | yes | no |
- Comparison sort lower bound: comparisons, .
- Insertion sort: shifts = inversions ; time . Max inversions .
- Selection sort: at most swaps.
- Merge of lists of sizes , : min comparisons, max .
- Merge sort worst case comparisons on : .
- Quicksort worst case: sorted or reverse sorted input with first or last pivot, and all-equal keys with Lomuto. Comparisons then .
- Quicksort recursing on the smaller part first: stack .
- Radix sort of keys in range to with base : .
- Counting sort: prefix sums number of keys ; scan input right to left for stability.
Selection and order statistics:
| Task | Cost |
|---|---|
| Min or max | comparisons |
| Min and max together (pairs) | |
| Second smallest (tournament) | |
| -th smallest, quickselect | average, worst |
| -th smallest, median of medians (groups of 5) | worst |
| Median of medians with groups of 3 |
Binary search:
- Worst case probes on sorted keys: .
- : average successful probes .
- Loop
while lo < hi,A[mid] < xthenlo = mid + 1elsehi = mid: returns first index with (lower bound). With<=it returns first index with (count of elements ).
Hashing
| Quantity | Value (load factor ) |
|---|---|
| Chaining, unsuccessful search | |
| Chaining, successful search | approx. |
| Chaining, worst case search | |
| Open addressing, unsuccessful (uniform hashing) | probes |
| Open addressing, successful | |
| Expected keys in a slot | |
| Expected colliding pairs (universal) |
| Probing | Probe | Distinct sequences | Problem |
|---|---|---|---|
| Linear | primary clustering | ||
| Quadratic | secondary clustering | ||
| Double | none of the above |
- Double hashing visits all slots iff : use prime, or with odd. always.
- Quadratic probing with can miss slots: . With prime and an empty slot is always found.
- Linear probing: an empty slot right after a run of full slots is filled next with probability .
- Deletion in open addressing: mark as deleted (tombstone), never empty, or later searches stop early.
- Universal family: for every . Example: , prime, , .
Greedy algorithms
| Problem | Greedy rule | Time |
|---|---|---|
| Activity selection | earliest finish time | |
| Interval partitioning (rooms) | sort by start; answer = max overlap | |
| Fractional knapsack | highest value/weight first | |
| Huffman coding | merge two smallest | |
| Optimal merge pattern | merge two smallest files | |
| Job sequencing with deadlines | highest profit, latest free slot | or |
| Min sum of completion times | shortest job first | |
| Min weighted completion | decreasing | |
| Min max lateness | earliest deadline first | |
| MST | Kruskal, Prim | see graphs |
- Greedy fails: 0/1 knapsack, coin change for non-canonical systems (, amount 15: greedy 6, optimum 3), activity selection by shortest or earliest start.
- Huffman on symbols: merges, internal nodes, max code length (Fibonacci frequencies).
- Huffman total bits sum of all internal node weights.
- Optimal merge cost = sum of all intermediate merged sizes.
Dynamic programming
Use DP when there are optimal substructure and overlapping subproblems.
| Problem | Recurrence | Time | Space |
|---|---|---|---|
| LCS | match: ; else | , for length only | |
| Edit distance | |||
| LIS | , with tails | ||
| 0/1 knapsack | pseudo-polynomial | ||
| Subset sum | |||
| Coin change (ways) | , coins in outer loop | ||
| Rod cutting | |||
| Matrix chain | |||
| Optimal BST | , Knuth |
Standard counts:
| Count | Value |
|---|---|
| Parenthesisations of matrices | Catalan : 1, 1, 2, 5, 14, 42 |
| BSTs on keys | : 1, 2, 5, 14, 42 for |
| Monotone lattice paths to | |
| Naive recursive Fibonacci calls for |
- Any distinct numbers contain a monotone subsequence of length (Erdos-Szekeres).
- Coin change ways: coin loop outside counts combinations; amount loop outside counts ordered sequences.
Divide and conquer
| Algorithm | Recurrence | Time |
|---|---|---|
| Merge sort | ||
| Max subarray (D&C) | ; Kadane | |
| Counting inversions | ||
| Closest pair | (presorted) | |
| Closest pair, re-sort strip each call | ||
| Karatsuba | ||
| Strassen | ||
| Fast power | ||
| Power with two recursive calls | ||
| Min and max (halves) | comparisons |
- Strassen: 7 products, 18 additions of blocks. Scalar multiplications ; additions .
- A block scheme with products runs in (when ); compare exponents.
- Closest pair strip: compare each point with at most the next 7 in order.
Graph traversals, MST and shortest paths
| Algorithm | Time (adjacency list) | Notes |
|---|---|---|
| BFS, DFS | matrix: | |
| Topological sort | DFS by decreasing finish time, or Kahn | |
| SCC (Kosaraju, Tarjan) | Kosaraju: DFS on , then on by decreasing finish | |
| Articulation points, bridges | DFS low values | |
| Prim, binary heap | Fibonacci heap ; matrix | |
| Kruskal | sorting dominates; union-find per op | |
| Dijkstra, binary heap | no negative edges | |
| Bellman-Ford | detects negative cycles | |
| DAG shortest paths | relax in topological order, any weights | |
| Floyd-Warshall | all pairs, negative edges allowed |
DFS edge classes (directed, by colour of when edge is seen):
| is | Edge | Note |
|---|---|---|
| white | tree | |
| gray (on stack) | back | cycle exists |
| black, | forward | |
| black, | cross |
- Undirected DFS: only tree and back edges. Undirected BFS: tree and cross edges; levels differ by at most 1.
- Component graph of SCCs is always a DAG.
- Articulation point: DFS root with children; non-root with a child having . Bridge : .
- Topological order count: adding an isolated vertex to a DAG on vertices multiplies the count by .
MST facts:
- Cut property: the lightest edge crossing any cut is in some MST.
- Cycle property: the unique heaviest edge on a cycle is in no MST.
- Distinct weights imply a unique MST. MST has edges.
- MST minimises the maximum edge on paths (bottleneck), but the MST path is not a shortest path.
Shortest path facts:
- Bellman-Ford: after round , all shortest paths with at most edges are correct. One extra round that still relaxes an edge means a negative cycle reachable from .
- Dijkstra can be wrong with a negative edge even without a negative cycle.
- Adding a constant to every edge can change shortest paths; multiplying by a positive constant cannot.
- Floyd-Warshall: allows intermediates only; a negative means a negative cycle.