STACK · The Engineering Codex
Ch 01 · CS Foundations
Chapter 01 · The bedrock

CS Foundations — the half of a degree you'll actually use

Algorithms, data structures, complexity, OS internals (processes, memory, files, I/O), and the cognitive vocabulary every other chapter assumes. Compact, deep, and reference-grade.

1.1 · Complexity & Big-O

ClassNameExample
$O(1)$ConstantHashmap get, array index.
$O(\log n)$LogarithmicBinary search, balanced BST lookup.
$O(n)$LinearOne pass over a list.
$O(n \log n)$LinearithmicMerge sort, quicksort average.
$O(n^2)$QuadraticNaive nested loops.
$O(2^n)$ExponentialRecursive Fibonacci, brute-force subset.
$O(n!)$FactorialBrute-force TSP.

Space complexity matters the same way. Amortised complexity matters too: a dynamic array's append is $O(1)$ amortised even though some appends trigger $O(n)$ resize.

1.2 · Data structures — the essential set

StructureLookupInsertUse when
Array / dynamic array$O(1)$ by index$O(1)$ amortised at endOrder matters, indices known.
Linked list$O(n)$$O(1)$ at known nodeFrequent middle inserts; cache-unfriendly.
Hashmap / dict$O(1)$ avg$O(1)$ avgKey→value lookups.
Tree map / sorted map$O(\log n)$$O(\log n)$Sorted iteration, range queries.
Heap / priority queue$O(\log n)$ pop$O(\log n)$Always need min/max next.
Trie$O(k)$ in key length$O(k)$Autocomplete, prefix matching.
Graph (adj list)$O(V+E)$ traversal$O(1)$ edge addRelationships, paths.
Bloom filter$O(k)$ probe$O(k)$Compact "definitely not / maybe" set.
HyperLogLog$O(1)$ approximate count$O(1)$Distinct counts on streams.
Skip list$O(\log n)$$O(\log n)$Sorted maps with simpler concurrency than BSTs (Redis).
B-tree / B+ tree$O(\log n)$$O(\log n)$Disk-based indexes (every relational DB).
LSM treefast writes, slower reads$O(1)$ appendWrite-heavy KV (RocksDB, Cassandra).
Roaring bitmap$O(1)$ bit opscompact membership at huge cardinalitiesSearch engines, analytics.

1.3 · Algorithm families to recognise on sight

FamilyPatternUsed in
SortingQuicksort, mergesort, timsort, radix.Every language stdlib.
SearchingLinear, binary, interpolation.Indices, autocomplete.
Graph traversalBFS, DFS.Web crawl, dependency walk.
Shortest pathDijkstra, A*, Bellman-Ford.Maps, routing, planners.
Dynamic programmingMemoise overlapping sub-problems.Edit distance, knapsack, DP-on-trees.
GreedyLocal-best choice → global solution (sometimes).Scheduling, Huffman coding.
Divide & conquerSplit, solve, combine.FFT, mergesort.
Sliding window / two pointersO(n) string / array scans.Substring search.
BacktrackingBuild, test, rewind.Solvers, constraint problems.
Union-Find / DSU$O(\alpha(n))$ union/find.Connectivity, Kruskal's MST.
Topological sortDAG ordering.Build systems, task schedulers.
Reservoir samplingUniform sample from a stream of unknown size.Online analytics.
Bit manipulation$x \& (x-1)$, popcount, XOR tricks.Compression, hashing, cryptography.

1.4 · Latency numbers every engineer should know

OperationOrder
L1 cache reference0.5 ns
Branch mispredict5 ns
L2 cache reference7 ns
Mutex lock/unlock25 ns
Main memory reference100 ns
Compress 1 KB (snappy)~3 μs
1 Gbps network: send 1 KB~10 μs
SSD random read~150 μs
Read 1 MB sequentially from SSD~1 ms
Round trip in same data centre~0.5 ms
HDD seek~10 ms
Round trip across continents~150 ms

1.5 · Processes & threads

Process A isolated address space thread 1 thread 2 shared heap · stacks separate Process B cannot see A's memory thread 1 Kernel scheduler, syscalls, drivers process table · page tables VFS · network stack
  • Process: isolated virtual address space, file descriptors, resources.
  • Thread: independent execution within a process; shares heap, separate stack.
  • Context switch: ~1–10 μs; far higher cost if it flushes cache or TLB.
  • Fork / exec: Unix model — fork copies (COW), exec replaces.
  • Green threads / fibers / goroutines: many user-space threads multiplexed on few OS threads.

1.6 · Memory model

SegmentWhat lives there
Text / codeRead-only executable instructions.
Data / BSSInitialised and zero-initialised globals.
HeapDynamic allocations; grows up.
Memory-mapped regionsmmap'd files, shared memory.
StackFunction frames; grows down; one per thread.
  • Virtual memory — every process sees a private address space; the MMU maps pages.
  • Pages — typically 4 KB; huge pages (2 MB / 1 GB) for DBs / JVMs.
  • Page fault — first touch loads from disk or zeros the page; major faults hit disk.
  • Copy-on-write — fork() shares pages until either side writes.
  • OOM killer — kernel reaps a process under memory pressure (configure with oom_score_adj).

1.7 · Files & I/O

I/O modelDefinitionUsed in
BlockingCall stops until I/O completes.Simple scripts.
Non-blockingCall returns immediately with WOULDBLOCK.Event loops.
I/O multiplexingOne thread watches many FDs (select/poll/epoll/kqueue).Nginx, Node, Redis.
Async I/O (io_uring, IOCP)Kernel completes work; userland polls a ring.Modern Linux services, Windows.
Memory-mapped (mmap)File as virtual memory; OS pages in.Databases, large reads.

1.8 · System calls you should recognise

SyscallWhat it does
open / openatAcquire a file descriptor.
read / write / pread / pwriteBytes in/out.
mmap / munmapMap a file (or anon memory).
fork / clone / execveCreate / replace processes.
epoll_create / epoll_ctl / epoll_waitEvent-loop primitives.
io_uringHigh-perf async I/O on Linux.
socket / bind / listen / accept / connectBSD sockets.
kill / sigactionSignals.
futexFast user-space mutex backing.

1.9 · Linux essentials a tech-savvy person never relearns

TopicTools
Processes / signalsps, top, htop, kill, strace, lsof.
I/O & diskiostat, iotop, du, df, fio, blktrace.
Networkss, tcpdump, wireshark, mtr, dig, ip.
Performanceperf, bpftrace, eBPF, flamegraph.
Filesystemsext4, XFS, ZFS, btrfs.
Init / servicessystemd, journalctl, units, sockets.
Cgroups / namespacesThe two primitives Docker is built on.

1.10 · Self-check

Q1 · Hash-map worst-case lookup is…
$O(1)$
$O(n)$
$O(\log n)$
$O(n \log n)$