--- title: 'Coding' description: 'There are only 6 structural families. Every pattern is a traversal or maintenance strategy over one of them.' sidebar: label: Introduction order: 1 icon: code --- ## Family 1 — Contiguous Linear (arrays, strings) *Structure property: O(1) index access, order is information.* | Pattern | What it really is | Recognition triggers | |---|---|---| | **Two Pointers** (7) | Converging/parallel index walk that prunes the O(n²) pair space using order | Sorted input · pair/triplet with target · palindrome · in-place partition | | **Sliding Window** (5) | Two pointers + incremental state between them (Two Pointers with a payload) | "Longest/shortest substring/subarray with property X" · contiguous constraint | | **Prefix Sum** (2) | Precomputed cumulative state → O(1) range queries | "Sum of range" · "subarray sum equals K" · repeated interval aggregation | | **Binary Search** (5) | Halving over ANY monotonic predicate — not just sorted arrays | Sorted/rotated input · "minimize the maximum" · answer space is monotonic (Koko) | | **Matrices** (3) | 2D index arithmetic; often a graph in disguise | Grid traversal/rotation/spiral · if cells have neighbors → it's Family 5 | **Systems anchor:** prefix sum is a materialized view; sliding window is stream processing with an eviction policy. ## Family 2 — Nodal Linear (linked lists) *Structure property: O(1) splice, no random access. Everything is pointer surgery.* | Pattern | What it really is | Recognition triggers | |---|---|---| | **Linked List** (5) | Three moves cover it all: fast/slow runners, reversal, dummy-head splicing | Cycle detection · middle/Nth-from-end · reverse/reorder · merge | **Systems anchor:** LRU Cache = hashmap + doubly-linked list — the one hybrid that appears constantly (it's a cache eviction index). ## Family 3 — Auxiliary Ordering Structures (stack, heap) *Structure property: you don't traverse them — you maintain them while traversing something else.* | Pattern | What it really is | Recognition triggers | |---|---|---| | **Stack** (5) | LIFO memory of "unresolved" items; monotonic stack = discard dominated candidates | Matching/nesting (parens) · "next greater element" · "previous smaller" · expression eval | | **Heap** (5) | Partial order — cheap access to extremum without full sort | "Kth largest/smallest" · "top K" · merge K streams · running median (two heaps) | **Systems anchor:** monotonic stack ≈ log compaction (drop entries superseded by newer state); heap ≈ priority scheduling / Dijkstra's frontier / timer wheels. ## Family 4 — Hierarchical (trees, tries) *Structure property: recursive shape — every node roots a subtree. Solutions are recurrences.* | Pattern | What it really is | Recognition triggers | |---|---|---| | **DFS on trees** (part of 13) | Post/pre/in-order recursion; answer composed from subtree answers | "Max depth / diameter / LCA / validate" · anything defined recursively | | **BFS on trees** (part of 8) | Level-order via queue | "Level by level" · "right side view" · minimum depth | | **Trie** (2) | Character-indexed tree; shared prefixes = shared paths | Prefix search · autocomplete · word dictionaries · many-string matching | | **BST specifically** | Sorted array in tree form — in-order traversal IS sorted order | "Kth smallest in BST" · range queries · validate | **Systems anchor:** trie ≈ radix routing table / IPLD path resolution; BST invariant ≈ index B-tree. ## Family 5 — Relational (graphs) *Structure property: arbitrary edges; must track visited. Trees are just acyclic connected graphs — same traversals, plus bookkeeping.* | Pattern | What it really is | Recognition triggers | |---|---|---| | **DFS on graphs** (13) | Exhaustive reachability; recursion + visited set | Islands/regions/flood fill · connectivity · cycle detection (directed: 3-color) | | **BFS on graphs** (8) | Frontier expansion → **shortest path in unweighted graphs, always** | "Minimum steps/moves" · multi-source spread (rotting oranges) · word ladder | | **Graphs** (6): Topological sort | DFS post-order reversed / Kahn's in-degree queue over a DAG | Dependencies · prerequisites · build order · "valid ordering exists?" | | **Graphs** (6): Union-Find | Incremental connectivity without traversal | Dynamic "same component?" queries · redundant edge · counting components | **Systems anchor:** topo sort = dependency resolution (your Turborepo build graph); union-find = partition detection; BFS = gossip propagation. A matrix with neighbor-moves is ALWAYS this family, not Family 1. ## Family 6 — Decision-Space (implicit graphs you build while exploring) *Structure property: nodes are STATES, not data. The structure doesn't exist until you walk it.* | Pattern | What it really is | Recognition triggers | |---|---|---| | **Backtracking** (6) | DFS over the state tree with undo; exhaustive enumeration | "All subsets/permutations/combinations" · constraint satisfaction · "generate all valid X" | | **Dynamic Programming** (10) | Backtracking + memoization — overlapping subproblems collapse the exponential tree | "Count ways" · "min/max cost to reach" · choices with shared substructure · optimal substructure | | **Greedy** (5) | DP where the local optimum provably suffices — no memo needed | Sort-then-commit works · exchange argument holds · intervals scheduling · jump game | **Systems anchor:** DP memo = idempotency cache over a deterministic state machine; backtracking = saga with compensating undo; greedy = eventually-consistent local decisions that provably converge. --- ## The Recognition Decision Tree (run this in the first 2 minutes — rubric axis #1) 1. **Contiguous array/string, no neighbor semantics?** → Family 1. Sorted or monotonic answer space → Binary Search. Pair/window constraint → Two/Sliding. Range sums → Prefix. 2. **Nodes with next-pointers?** → Family 2. Reach for fast/slow or dummy-head before anything clever. 3. **Need "next greater," nesting, or top-K while scanning?** → Family 3 auxiliary structure on top of whatever you're traversing. 4. **Recursive shape (tree/prefix data)?** → Family 4. Ask: does the answer compose from subtrees (DFS) or from levels (BFS)? 5. **Arbitrary connections, grids with movement, dependencies?** → Family 5. Unweighted shortest = BFS. Ordering over DAG = topo. Dynamic connectivity = union-find. Otherwise DFS. 6. **Enumerate or optimize over CHOICES?** → Family 6. All solutions → backtracking. Overlapping subproblems → DP. Provable local choice → greedy. ## The Escalation Lattice (when stuck, patterns upgrade along these edges) - Two Pointers —*add state*→ Sliding Window —*add aggregation*→ Prefix Sum - Brute-force scan —*monotonic predicate*→ Binary Search on answer - Tree DFS —*add visited set*→ Graph DFS —*add undo*→ Backtracking —*add memo*→ DP —*add proof*→ Greedy - Sort —*need only extremum*→ Heap —*need running extremes*→ Monotonic Stack - BFS —*add weights*→ Dijkstra (= BFS with a heap: Families 3+5 composed) Memorize the lattice, not 16 patterns. In the interview, naming the family out loud ("this is a state-space problem, so backtracking or DP depending on overlap") IS the recognition signal the rubric scores.