Put knowledge_vault/computer_science/algorithms-core.md
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364# Algorithms — core reference (CS vault)
## Asymptotic notation
- **O (big-O)** — upper bound. f(n) = O(g(n)) iff ∃ c>0, n₀: f(n) ≤ c·g(n) for all n ≥ n₀.- **Ω** — lower bound; **Θ** — tight bound (both O and Ω).- Common growth rates, slowest to fastest: O(1), O(log n), O(n), O(n log n), O(n²), O(n³), O(2ⁿ), O(n!).- Rule of thumb at 10⁸ simple ops/sec (single core): n = 20 → O(2ⁿ) OK; n = 500 → O(n³) OK; n = 10⁵ → O(n²) OK; n = 10⁷ → O(n log n).
## Sorting
| Algorithm | Best | Average | Worst | Space | Stable ||---|---|---|---|---|---|| Merge sort | O(n log n) | O(n log n) | O(n log n) | O(n) | yes || Quicksort | O(n log n) | O(n log n) | O(n²) | O(log n) | no || Heapsort | O(n log n) | O(n log n) | O(n log n) | O(1) | no || Insertion sort | O(n) | O(n²) | O(n²) | O(1) | yes |
- Quicksort pivot: median-of-three or randomize to avoid the O(n²) adversarial case.- Merge sort is the baseline for external sorting (data larger than RAM): sequential I/O.- When input is nearly sorted, insertion sort beats everything: O(n + inversions).
## Graph algorithms
- **BFS** (queue): unweighted shortest path. O(V+E). Also level-order traversal.- **DFS** (stack/recursion): cycle detection, topological sort (on finish order, DAGs), connected components. O(V+E).- **Dijkstra** (binary heap): non-negative weights, single source. O((V+E) log V). With negative edges use Bellman-Ford: O(V·E), also detects negative cycles.- **A\***: Dijkstra + admissible heuristic h(n) that never overestimates; expands far fewer nodes when h is good (Manhattan/Euclidean distance are admissible on grids).- **Union-Find** with path compression + union by rank: amortized O(α(n)) ≈ O(1) per op. Backbone of Kruskal's MST and connected-component labeling.
## Dynamic programming
Recipe: (1) define the state precisely; (2) write the recurrence; (3) identify base cases; (4) choose memoized recursion (top-down) or table (bottom-up); (5) the answer is the state(s) you declared.
| Problem | State | Recurrence | Complexity ||---|---|---|---|| 0/1 knapsack | (i, w) = best value using items ≤ i, capacity w | V[i][w] = max(V[i-1][w], V[i-1][w-wᵢ]+vᵢ) | O(n·W) || Edit distance | (i, j) prefixes of A, B | d[i][j] = 1 + min(d[i-1][j], d[i][j-1], d[i-1][j-1] − (A[i]==B[j])) | O(len A · len B) || Longest common subsequence | (i, j) | L[i][j] = L[i-1][j-1]+1 if A[i]==B[j] else max(L[i-1][j], L[i][j-1]) | O(m·n) || Fibonacci | k | F(k) = F(k-1)+F(k-2) | O(n) time O(1) space; O(log n) with matrix power |
## Greedy and when it fails
A greedy algorithm is correct when the problem has the **greedy-choice property** and **optimal substructure** (prove by exchange argument). Counter-example to memorize: greedy by value/weight ratio fails 0/1 knapsack — it misses inputs where a slightly worse ratio now unlocks better capacity use later. Fractional knapsack, by contrast, is provably greedy-correct.
## P vs NP (working knowledge)
- P: solvable in polynomial time. NP: verifiable in polynomial time. NP-complete: every NP problem reduces to it (SAT is the root; Cook–Levin 1971).- Reduction pattern: to prove X NP-hard, reduce a known NP-complete Y to X in polytime. Common chains: SAT → 3-SAT → CLIQUE → VERTEX-COVER; 3-SAT → SUBSET-SUM → KNAPSACK (decision form); 3-SAT → 3-COLORING → scheduling variants.- Practical consequence: if your optimization is NP-hard, stop hunting for exact polytime algorithms and reach for approximation ratios, branch-and-bound, or evolutionary search (see §EVO_OPT:DEAP, §EVO_NEURO:EVOTORCH).
## Hashing
- Average O(1) lookup under simple uniform hashing; worst O(n) without care.- Collision handling: chaining (load factor α = n/m, expect ~α probe length) or open addressing (linear probing suffers primary clustering; double hashing does not).- Python `dict` = open addressing with perturbation; Java `HashMap` = chaining, treeifies bins ≥ 8.- sha256 is a hash WITHOUT structure guarantees — it exists for integrity/provenance (this drive uses it everywhere), not for lookup tables.
## Concrete numbers worth knowing on this hardware
- Reading 1 GB from USB 3.0 (~400 MB/s): ~2.5 s. From USB 2.0 (~35 MB/s): ~30 s. This is why symbols resolve to specific files rather than scanning the vault.- sha256 in software: ~1–2 GB/s per core; hashing the 5.8 GB Ornith GGUF takes ~4–6 s — cheap enough for every REST audit.knowledge_vault/computer_science/algorithms-core.mdAdded+64