Practice tool
Printable cheat sheets
Tick the sheets you want, choose columns and text size, then print or save as PDF. Each chapter sheet is its key takeaways plus the flashcard answers.
Week 1 · Python Refresher
Key points
- Judge algorithms by how the number of operations grows with input size, not by seconds on one machine.
- Euclid's gcd is fast because
modcollapses many subtractions into one step: steps ∝ number of digits, not the value. - A number is prime if no integer in 2…√n divides it; stop early at the first factor.
- Use
try / except / else / finallyto handle runtime errors without crashing. - Classes bundle data with the functions that operate on it — the basis for every data structure we build later.
Quick recall
- Mutable vs immutable: which of list, tuple, str, dict, set can change in place?
- Mutable: list, dict, set. Immutable: tuple, str (and int, float, bool).
- What does
b = ado whenais a list? - Nothing is copied:
aandbname the SAME list, so changing one changes the other. Usea[:]orlist(a)for a copy. - Why is
def f(x, acc=[])dangerous? - The default list is created once, when the function is defined, and shared by every call that omits
acc. - Euclid's gcd step and its cost
- gcd(a, b) = gcd(b, a mod b), gcd(a, 0) = a. Takes O(log min(a, b)) steps.
- Cost of
x in my_listvsx in my_set - List: O(n) scan. Set / dict: O(1) average (hashing).
- How do you read
lst[::-1],lst[1:-1],lst[::2]? - Reversed copy; everything except first and last; every second element. Slicing makes a new list.
Week 2 · Complexity, Notations, Sorting & Searching
Key points
- Compare algorithms by growth rate of the worst-case operation count; use O (upper), Ω (lower) and Θ (tight).
- Binary search needs a sorted list and takes O(log n); linear search works anywhere in O(n).
- Selection, insertion and bubble sort are O(n²). Insertion sort is Θ(n) on sorted input.
- Merge sort is Θ(n log n) always but uses O(n) extra space; quicksort is O(n log n) on average, O(n²) worst case, in place.
- Comparison-based sorting cannot beat Ω(n log n).
Quick recall
- Definition of f(n) = O(g(n))
- There are constants c > 0 and n0 such that f(n) ≤ c·g(n) for all n ≥ n0 (an upper bound).
- Ω and Θ in one line each
- Ω(g): lower bound (f ≥ c·g eventually). Θ(g): both O(g) and Ω(g) — a tight bound.
- Growth order from slowest to fastest growing
- 1 < log n < √n < n < n log n < n² < n³ < 2ⁿ < n!
- Selection sort: time and swaps
- Θ(n²) comparisons always; at most n − 1 swaps. Not adaptive.
- Insertion sort: best / worst case
- Best O(n) on already sorted input, worst O(n²) on reversed input. Stable, in place.
- Merge sort: time, extra space, stability
- Θ(n log n) always; O(n) extra space; stable.
- Quicksort: average vs worst case
- Average O(n log n); worst O(n²) when pivots split badly (e.g. sorted input with first-element pivot).
- Binary search requirement and cost
- Needs a SORTED sequence with O(1) indexing. Halves the range each step: O(log n).
- What is a stable sort?
- Equal keys keep their original relative order. Matters when sorting by a second key after the first.
Week 3 · Arrays, Lists, Stacks, Queues, Hashing
Key points
- Arrays give O(1) indexing, but inserting or deleting in the middle shifts items; Python lists append in amortised O(1).
- Linked lists make local insert/delete O(1) but give up O(1) access.
- A stack is LIFO (push/pop); a queue is FIFO (enqueue/dequeue) — use
dequefor O(1) at both ends. - Hash tables give O(1) average lookup/insert/delete; collisions are resolved by probing or chaining, and the load factor must stay small.
- Beware aliasing:
B = Ashares a list, and[[0]*3]*2shares rows.
Quick recall
- Array vs linked list: access and insert-at-front
- Array: O(1) access, O(n) insert at front. Linked list: O(n) access, O(1) insert at front.
- Amortised cost of
appendon a Python list - O(1) amortised: the array doubles when full, so the occasional O(n) copy is spread over many appends.
- Stack: discipline and operations
- LIFO. push / pop / peek — all O(1). Uses: undo, bracket matching, DFS, expression evaluation.
- Queue: discipline and the right Python tool
- FIFO. Use
collections.deque(O(1) popleft);list.pop(0)is O(n). Uses: BFS, scheduling. - What does a hash function do and what is a collision?
- Maps a key to a table slot. A collision is two different keys landing in the same slot.
- Two ways to resolve collisions
- Chaining (each slot holds a list) and open addressing (probe for another free slot: linear, quadratic, double hashing).
- Load factor α and why it matters
- α = items / slots. Keep α small (resize when it grows) so the expected cost per lookup stays O(1).
- Which Python keys can go in a dict or set?
- Hashable ones: immutable objects like int, str, tuple of hashables. Not list, dict or set.
Week 4 · Graph Algorithms
Key points
- A graph is vertices + edges; prefer adjacency lists (Θ(n + m)) over matrices (Θ(n²)) unless the graph is dense.
- BFS: queue, explores by layers, gives fewest-edge distances. DFS: stack/recursion, explores deep then backtracks. Both are O(n + m).
- Searches answer reachability, connected components, cycle detection, and (BFS) unweighted shortest paths.
- Sum of degrees is 2m; a tree on n vertices has n − 1 edges.
Quick recall
- Adjacency matrix vs adjacency list: space and edge test
- Matrix: Θ(n²) space, O(1) 'is there an edge'. List: Θ(n + m) space, O(deg) edge test, fast to iterate neighbours.
- BFS: data structure, finds what, cost
- Queue; visits vertices in order of distance from the source, so it gives shortest paths in UNWEIGHTED graphs. O(n + m) with adjacency lists.
- DFS: data structure and what it gives
- Stack / recursion. Gives reachability, connected components, a DFS tree with pre/post numbers. O(n + m).
- Tree edge, back edge in a DFS of an undirected graph
- Tree edge discovers a new vertex; a back edge goes to an already visited ancestor and signals a CYCLE.
- How do you detect a cycle in a directed graph?
- DFS: an edge to a vertex that is currently on the recursion stack (grey). Or topological sort fails to include all vertices.
- Connected components: how to count them
- Run BFS/DFS from every unvisited vertex; the number of starts is the number of components. O(n + m).
Week 5 · Graph Algorithms (Continued)
Key points
- A DAG has no directed cycle; a topological order exists iff the graph is a DAG, and can be found in O(n + m) with Kahn's algorithm or reverse DFS finish order.
- Longest paths in a DAG are easy: process in topological order (the first taste of dynamic programming).
- Dijkstra: greedy, picks the closest unfinished vertex then relaxes edges; needs non-negative weights; O(n²) simple, O((n + m) log n) with a heap.
- Bellman–Ford handles negative edges in O(nm); Floyd–Warshall gives all-pairs distances in O(n³).
Quick recall
- Topological order: what it is and when it exists
- A vertex ordering where every edge u → v has u before v. Exists iff the directed graph is acyclic (a DAG).
- Two ways to compute a topological order
- Kahn: repeatedly remove a vertex of indegree 0. Or DFS: list vertices in decreasing post-order finish time.
- Longest path in a DAG
- Process vertices in topological order and relax: longest[v] = max over u → v of longest[u] + 1. O(n + m).
- Dijkstra: the invariant and the restriction
- Always settle the unsettled vertex with the smallest tentative distance. Requires NON-NEGATIVE edge weights.
- Dijkstra with a heap: running time
- O((n + m) log n) with a binary heap; O(n²) with a plain array scan.
- Bellman-Ford: idea, cost, and extra power
- Relax all edges n − 1 times: O(nm). Handles negative weights and detects negative cycles.
- Floyd-Warshall: what and cost
- All-pairs shortest paths: allow intermediate vertices 1..k one k at a time. Θ(n³) time, Θ(n²) space.
Week 6 · Union-Find, Priority Queue, Heap, BST
Key points
- Union–Find supports
findandunion; with union-by-size and path compression, operations are almost O(1). - A priority queue serves the highest-priority item; a binary heap implements insert and delete in O(log n), stored in a plain array with children at 2i+1 and 2i+2.
heapifybuilds a heap in O(n); heap sort is O(n log n) in place.- A BST gives search/insert/delete in O(height); in-order traversal lists keys in sorted order; an unlucky insertion order makes height n.
Quick recall
- Union-Find operations and the two tricks
- find(x), union(x, y). Union by size/rank + path compression gives almost constant amortised time (inverse Ackermann).
- Kruskal's algorithm in one sentence
- Sort edges by weight; add an edge if it joins two different components (check with union-find). O(m log m).
- Priority queue operations and heap costs
- insert and delete-min are O(log n); find-min is O(1); building a heap from n items is O(n).
- Heap shape and index arithmetic (0-based array)
- A complete binary tree stored in an array: parent(i) = (i − 1)//2, children 2i + 1 and 2i + 2.
- Min-heap property
- Every node is ≤ its children, so the minimum is at the root. It does NOT mean the array is sorted.
- Binary search tree property and operation cost
- Left subtree < node < right subtree. find / insert / delete cost O(height): O(log n) if balanced, O(n) if skewed.
- What traversal of a BST gives sorted order?
- In-order (left, node, right).
- BST delete: the node has two children — what now?
- Replace its value with the in-order successor (minimum of the right subtree) or predecessor, then delete that node.
Week 7 · Balanced Trees & Greedy Algorithms
Key points
- AVL trees keep |height(left) − height(right)| ≤ 1 at every node using single/double rotations, so height is O(log n) and every operation is O(log n) worst case.
- Greedy = take the locally best choice and never undo it. It is only correct when you can prove the greedy-choice property (exchange argument) — coin change with arbitrary coins is a counter-example.
- Interval scheduling: sort by finish time, take every compatible interval. O(n log n).
- MST: Kruskal (sort edges + Union–Find) and Prim (grow a tree with a heap) both rely on the cut property.
- Huffman coding merges the two rarest symbols repeatedly, giving an optimal prefix-free code.
Quick recall
- AVL tree balance condition
- For every node, the heights of the left and right subtrees differ by at most 1. Height is O(log n).
- When do you use a single rotation vs a double rotation in an AVL tree?
- Single rotation for LL / RR imbalance (the heavy grandchild is on the outside); double for LR / RL (inside).
- Greedy: what makes a problem suitable?
- Greedy-choice property (a locally best choice can be extended to an optimal solution) plus optimal substructure. Needs a proof — often an exchange argument.
- Interval scheduling: the greedy rule
- Sort by FINISH time; repeatedly take the earliest-finishing interval compatible with those chosen.
- Minimum spanning tree: Prim vs Kruskal
- Prim grows one tree by the cheapest crossing edge (heap, O(m log n)); Kruskal merges components by cheapest edge (union-find, O(m log m)).
- Huffman coding idea
- Repeatedly merge the two lowest-frequency nodes. Frequent symbols get short prefix-free codes; yields an optimal prefix code.
Week 8 · Divide and Conquer
Key points
- Divide, conquer recursively, combine. The running time is captured by a recurrence like
T(n) = a·T(n/b) + f(n). - Master theorem for
a·T(n/b) + n^d: compareawithb^d→ Θ(n^d), Θ(n^d log n) or Θ(n^(log_b a)). - Fast exponentiation: O(log n). Counting inversions: O(n log n) by piggybacking on merge sort.
- Quickselect finds the k-th smallest in expected O(n); median-of-medians makes it worst-case O(n).
- Karatsuba trades four sub-multiplications for three: Θ(n^1.585).
Quick recall
- Master theorem for T(n) = a·T(n/b) + n^d
- a < b^d → Θ(n^d); a = b^d → Θ(n^d log n); a > b^d → Θ(n^(log_b a)).
- Recurrence and solution of merge sort
- T(n) = 2T(n/2) + n → Θ(n log n).
- Recurrence and solution of binary search
- T(n) = T(n/2) + 1 → Θ(log n).
- Fast exponentiation: idea and cost
- xⁿ = (x^(n/2))² (times x if n odd), computing the half power ONCE. O(log n) multiplications.
- Counting inversions in O(n log n)
- Merge sort; when an element of the right half is placed, add the number of elements still waiting in the left half.
- Quickselect: expected and worst case
- Expected O(n) with a random pivot; worst O(n²). Median-of-medians pivot makes it worst-case O(n).
- Karatsuba's trick
- Compute (a+b)(c+d) − ac − bd instead of ad + bc: 3 half-size products instead of 4, so Θ(n^1.585).
Week 9 · Dynamic Programming
Key points
- Naive recursion re-solves the same subproblems; DP solves each once and stores the answers — top-down (memoisation) or bottom-up (table).
- The recipe: inductive definition → overlapping subproblems → fill order → read the answer. Cost = number of subproblems × work each.
- LCS / longest common subword / edit distance fill an m×n table in O(mn).
- Matrix chain: O(n²) subproblems with O(n) splits each ⇒ O(n³). Knapsack: O(nW), pseudo-polynomial.
- Where greedy fails (arbitrary coin change), DP still finds the optimum.
Quick recall
- Two properties a DP problem must have
- Optimal substructure and overlapping subproblems.
- Memoisation vs tabulation
- Memoisation: top-down recursion + cache. Tabulation: bottom-up table filled in dependency order. Same asymptotic cost.
- Steps to design a DP
- 1) define the subproblem 2) write the recurrence 3) base cases 4) order of evaluation 5) where the answer sits.
- Longest common subsequence recurrence
- If x[i] = y[j]: L(i, j) = 1 + L(i+1, j+1); else max(L(i+1, j), L(i, j+1)). Θ(mn).
- Edit distance recurrence
- If equal: E(i−1, j−1); else 1 + min(E(i−1, j) [delete], E(i, j−1) [insert], E(i−1, j−1) [replace]).
- 0/1 knapsack recurrence
- K(i, w) = max(K(i−1, w), v_i + K(i−1, w − w_i)) when w_i ≤ w. Θ(nW) — pseudo-polynomial.
- Coin change (min coins) recurrence
- C(0) = 0; C(a) = 1 + min over coins c ≤ a of C(a − c). Greedy fails for some coin systems, DP does not.
- Naive recursive Fibonacci vs memoised
- Naive: Θ(φⁿ) time (exponential). Memoised / tabulated: Θ(n).
Week 10 · String / Pattern Matching
Key points
- Pattern matching asks where a pattern of length m occurs in a text of length n. Brute force is O(nm).
- Boyer–Moore compares right to left and uses the bad-character rule to skip ahead — typically sub-linear.
- KMP precomputes a failure function in O(m) and then scans the text in O(n) with no backtracking.
- Tries index many words by their prefixes: lookup in O(word length), natural for autocomplete.
Quick recall
- Naive pattern matching cost
- Compare the pattern at every shift: O(mn) worst case for text length n and pattern length m.
- KMP failure (prefix) function π[i]
- Length of the longest proper prefix of the pattern that is also a suffix of pattern[0..i].
- KMP total running time
- O(n + m): the text pointer never moves backward, and building the failure table is O(m).
- Rabin-Karp idea
- Compare rolling hashes of the pattern and each text window; verify only on a hash match. Expected O(n + m).
- Trie: what it stores and lookup cost
- A tree of characters sharing common prefixes. Lookup / insert cost O(length of the word), independent of the number of words.
Week 11 · Network Flows, LP & Complexity Classes
Key points
- A flow obeys capacity and conservation constraints; the max flow is found by repeatedly augmenting along s–t paths in the residual graph (Edmonds–Karp: BFS paths, O(V·E²)).
- Max-flow = min-cut: the best flow equals the capacity of the cheapest s–t cut. Matching and many other problems reduce to flow.
- Linear programs optimise linear objectives over polytopes; optimum at a corner; polynomial-time solvable. Requiring integers (ILP) makes them NP-hard.
- P: solvable fast. NP: solutions verifiable fast. NP-complete: hardest in NP — a fast algorithm for one gives one for all. Whether P = NP is open.
- Reductions transfer hardness: reduce a known hard problem to yours.
Quick recall
- Max-flow min-cut theorem
- The value of a maximum s–t flow equals the capacity of a minimum s–t cut.
- Ford-Fulkerson in one line
- Repeatedly find an augmenting path in the residual graph and push flow along it. With BFS (Edmonds-Karp): O(nm²).
- Bipartite matching via flow
- Source → left vertices → right vertices → sink, all capacities 1. Max flow = size of a maximum matching.
- P, NP, NP-complete
- P: solvable in polynomial time. NP: solutions verifiable in polynomial time. NP-complete: in NP and every NP problem reduces to it.
- What does a polynomial-time reduction A ≤ B tell you?
- If B is solvable in polynomial time so is A; equivalently, if A is hard then B is hard.
- Name three classic NP-complete problems
- SAT / 3-SAT, Clique (or Independent Set / Vertex Cover), Hamiltonian Path / TSP decision version, Subset Sum.
Week 12 · Summary & Final Review
Key points
- Always estimate cost first: counting operations and spotting n, n log n, n² or exponential growth tells you whether an approach will work.
- Recognise the pattern: halving → log; sort first; graph exploration → BFS/DFS; greedy needs proof; overlapping subproblems → DP; capacities → flow.
- Data structures are tools: pick one so the operation you repeat most often is cheap.
- Some problems (NP-complete) have no known fast algorithm — recognise them, then approximate or restrict.
Quick recall
- BFS vs DFS vs Dijkstra: which for 'fewest edges'?
- BFS. DFS does not give shortest paths; Dijkstra is for non-negative weights.
- Which technique when sub-problems overlap?
- Dynamic programming (cache the overlapping subproblems). Divide and conquer assumes independent subproblems.
- Sorting lower bound
- Any comparison-based sort needs Ω(n log n) comparisons in the worst case (decision tree has ≥ n! leaves).
- Data structure for 'repeatedly get the smallest'?
- A min-heap (priority queue): O(log n) per insert and delete-min.
- Data structure for 'are these two items connected?' with merging groups
- Union-Find (disjoint sets).
- Data structure for fast membership and counting by key
- Hash table (Python
set/dict/Counter): O(1) average.
Bonus · Recursion & Backtracking (bonus)
Key points
- A recursive function needs a base case and a call on a smaller input. The call stack remembers unfinished calls.
- Draw the calls as a tree of choices: subsets have 2ⁿ leaves, permutations n!.
- Backtracking = choose, explore, un-choose, and record a COPY of the path when it is complete.
- Pruning cuts branches that cannot succeed; it is what makes N-Queens and Sudoku practical.
- Python recursion is limited to about 1000 frames; use loops, an explicit stack or
lru_cache(memoisation) when needed.
Practice · Practice: Which Technique?
Key points
- Read the problem for clues: sorted data, shortest/fewest, dependencies, connect-everything, overlapping subproblems, 'always the largest', matching/capacity.
- Estimate the brute-force cost first; with n around 10⁵ or more you need roughly O(n log n).
- Pick the data structure for the operation you repeat most: hash for lookup, heap for extreme, union–find for groups, trie for prefixes.
- Keep practising on varied problems — recognition improves with volume.
Pattern playbook · signals and costs
Spot the signal
| When you see… | Reach for |
|---|---|
| sorted input, pair/triple wanted | Two pointers |
| longest / shortest contiguous block | Sliding window |
| many range sums, or 'subarrays with sum k' | Prefix sums + hash map |
| 'seen before?', counts, duplicates | Hash map / set |
| next greater / smaller, spans | Monotonic stack |
| 'minimum possible maximum', yes/no check is monotone | Binary search on the answer |
| overlapping intervals / schedules | Sort, then sweep |
| fewest steps in an unweighted graph or grid | BFS |
| regions, reachability, prerequisites | DFS / topological order |
| k best, repeated min or max | Heap |
| merging groups, redundant edge | Union-Find |
| generate every arrangement, n ≤ 20 | Backtracking |
| count ways, min cost, overlapping sub-problems | Dynamic programming |
| local choice provably safe | Greedy |
| weighted edges, non-negative | Dijkstra |
Cost of each pattern
| Pattern | Time / space |
|---|---|
| Two pointers | O(n) time, O(1) space |
| Sliding window | O(n) time, O(window) space |
| Prefix sums | O(n) build, O(1) per query |
| Hash map: count and complement | O(n) time, O(n) space |
| Monotonic stack | O(n) time, O(n) space |
| Binary search on the answer | O(n log range) |
| Sort, then sweep (intervals) | O(n log n) for the sort, O(n) sweep |
| BFS: shortest path, levels, grids | O(n + m) |
| DFS: components, cycles, topological order | O(n + m) |
| Heap / top-k | O(n log k) |
| Union-Find | almost O(1) amortised per operation |
| Backtracking | exponential in the worst case; pruning is what makes it usable |
| Dynamic programming | O(number of states × work per state) |
| Greedy | usually O(n log n) for the sort |
| Weighted shortest paths | O((n + m) log n) |
Complexity at a glance
Searching & sorting
| Algorithm | Best | Average | Worst | Notes |
|---|---|---|---|---|
| Linear search | O(1) | O(n) | O(n) | any order |
| Binary search | O(1) | O(log n) | O(log n) | sorted array only |
| Selection sort | O(n²) | O(n²) | O(n²) | few swaps, not stable |
| Insertion sort | O(n) | O(n²) | O(n²) | fast on nearly sorted input, stable |
| Bubble sort | O(n) | O(n²) | O(n²) | with early exit |
| Merge sort | O(n log n) | O(n log n) | O(n log n) | O(n) extra space, stable |
| Quicksort | O(n log n) | O(n log n) | O(n²) | bad pivots (e.g. sorted input, first-element pivot) give the worst case |
Data structures
| Operation | Cost | Notes |
|---|---|---|
| list: index, append | O(1) | append is amortised O(1) |
list: insert/delete in the middle, x in list | O(n) | items shift / full scan |
| dict / set: lookup, insert, delete | O(1) average | O(n) in the worst case (many collisions) |
| deque: push/pop at either end | O(1) | use for queues, not list.pop(0) |
| heap: push, pop-min | O(log n) | peek is O(1); building from n items is O(n) |
| BST: search, insert, delete | O(h) | h = height: O(log n) if balanced, O(n) if skewed |
| AVL tree: search, insert, delete | O(log n) | rotations keep the height logarithmic |
| Union–Find (path compression + union by size) | ≈ O(1) | amortised, inverse-Ackermann growth |
Graph algorithms
| Algorithm | Time | Notes |
|---|---|---|
| BFS / DFS | O(V + E) | adjacency list; O(V²) with a matrix |
| Topological order | O(V + E) | DAGs only |
| Dijkstra | O((V + E) log V) | heap; non-negative weights |
| Bellman–Ford | O(V·E) | negative weights allowed, detects negative cycles |
| Floyd–Warshall | O(V³) | all pairs |
| Prim (heap) / Kruskal | O(E log V) | minimum spanning tree |
Dynamic programming, strings & more
| Problem | Time | Notes |
|---|---|---|
| LCS, edit distance, longest common subword | O(m·n) | table of size m × n |
| Matrix chain multiplication | O(n³) | O(n²) subproblems × O(n) splits |
| 0/1 knapsack | O(n·W) | pseudo-polynomial in W |
| Naive string matching | O(n·m) | try every shift |
| Knuth–Morris–Pratt | O(n + m) | never moves backwards in the text |
| Fast exponentiation | O(log n) | square-and-multiply |
Recurrences
| Recurrence | Solves to | Typical algorithm |
|---|---|---|
| T(n) = T(n/2) + O(1) | O(log n) | binary search, fast exponentiation |
| T(n) = T(n−1) + O(1) | O(n) | linear recursion |
| T(n) = T(n−1) + O(n) | O(n²) | quicksort worst case, insertion-style recursion |
| T(n) = 2T(n/2) + O(n) | O(n log n) | merge sort, quicksort best case |
| T(n) = 2T(n/2) + O(1) | O(n) | tree traversal |
| T(n) = 2T(n−1) + O(1) | O(2ⁿ) | naive subsets, naive Fibonacci-style blow-up |