Foundations of ComputingDeeper

Kayavak / Foundations of Computing / CS·03 Data Structures / Deeper

Deeper · Foundations of Computing

Data Structures

The questions the chapter doesn't stop for: why this exists, the model to keep in your head, what changes when an assumption does, how sure we are of each claim, and what's still open. Read it after the chapter; back to the chapter.

Why does this exist?

A computer's memory is one long row of numbered bytes. That's all the hardware offers. Every data structure is an answer to the same question: how do I lay data out in that row so the operations I need are cheap?

The answers arrived as problems demanded them. Arrays came straight from how memory is addressed: item i lives at start + i × size, so FORTRAN (1957) made them its central type. Linked lists were invented by Allen Newell, Cliff Shaw and Herbert Simon for their Information Processing Language (1955–56), because their early AI programs needed structures that grew and changed shape while running. Hashing appears in an internal IBM memo by Hans Peter Luhn in 1953: turn a key into a number and use it as an address. Balanced trees followed when sorted data had to stay fast under inserts: AVL trees (Georgy Adelson-Velsky and Evgenii Landis, 1962), B-trees for disks (Rudolf Bayer and Edward McCreight, 1972), red-black trees (Leonidas Guibas and Robert Sedgewick, 1978). J. W. J. Williams introduced the binary heap with heapsort in 1964.

None of these replaced the others, because each makes a different operation cheap at another's expense.

The mental model

Try it yourself first: write your own model in the Mental Model Explorer, then compare.

Choose a data structure by the operations you'll do most, then pay for it in the operations you do least.

Question Answer
What is it? A layout of data in memory plus the rules for keeping that layout valid
Problem it solves Making the frequent operations (find, insert, remove, iterate in order, take the smallest) cheap
Parts Contiguous blocks (arrays), pointers between nodes (lists, trees, graphs), a function from keys to positions (hashing)
How it works Each structure keeps an invariant: sorted order, a balance rule, a heap order, a load factor. Operations restore it
Assumptions Memory access costs about the same everywhere; you know your workload
When they change Caches make nearby memory far cheaper than far memory, so arrays beat linked structures more often than Big-O predicts
Where it fails Adversarial input (hash flooding), concurrent writers, data too big for memory (then B-trees and LSM trees, Databases)
Related ideas Algorithms (ch04) assume a structure; locality (ch07); databases' indexes are these structures on disk

What if?

What if a dynamic array grew by a fixed 10 slots instead of doubling?

Reason it through, then open

Appending n items would copy 10 + 20 + 30 + … items, about n²/20 in total: quadratic. Appending a million items would copy around fifty billion elements. Doubling (or any constant factor, like Java's 1.5×) keeps the total copying below a small multiple of n, which is what makes append amortised O(1). See the derivation below.

What if memory had no caches?

Reason it through, then open

Every access would cost the same main-memory trip, around 100 nanoseconds. Arrays would lose much of their real-world advantage over linked lists, because their speed comes from loading 64 bytes at a time and prefetching the next line. Big-O would predict running time much better than it does today, and everything would be far slower.

What if an attacker chooses your hash table's keys?

Reason it through, then open

They can pick keys that all land in one bucket, turning O(1) lookups into O(n) scans: a web server parsing request parameters into a hash map can be slowed to a crawl (the 2011 "hash flooding" attacks on many web platforms). The defences are a secret, randomised hash seed per process (Python, Rust, Go) or tree-shaped buckets with a log n worst case (Java 8's HashMap).

Where the boundary is

Aspect Hash table Balanced search tree
Find, insert, remove O(1) average, O(n) worst O(log n) always
Ordered iteration, ranges, "next larger key" No Yes
Needs from keys A good hash and consistent equality A consistent ordering
Memory Spare capacity (load factor) A node per entry, with pointers
Pick it when You only ask "is it there?" and "what's its value?" You need order, ranges or a guaranteed worst case

Derive it

Why doubling makes append amortised O(1).

  1. Start with capacity 1 and double whenever the array is full. Appending n items triggers copies when the size reaches 1, 2, 4, …, up to the largest power of two below n.
  2. Each resize copies every current element: 1 + 2 + 4 + … + 2ᵏ where 2ᵏ < n.
  3. That geometric sum equals 2ᵏ⁺¹ − 1, which is less than 2n.
  4. So n appends cost n writes plus fewer than 2n copies: under 3n operations, a constant per append on average.
  5. Any growth factor r > 1 gives the same shape, with total copying under n/(r − 1); a fixed increment doesn't, because the sum 10 + 20 + … grows with the square of n.

How sure are we?

Claim How it's known Where from
Doubling gives amortised O(1) append Theorem The geometric sum above
Hash tables are O(1) on average Theorem, with an assumption True if the hash spreads keys uniformly; false for adversarial or poorly hashed keys
Arrays usually beat linked lists in practice Measured The chapter's lab; widely reproduced, because of caches and prefetching
Linked lists, hashing and B-trees origins Historical IPL (1955–56), Luhn's memo (1953), Bayer and McCreight (1972)

Still open

Data structures for modern hardware are an active area: cache-oblivious layouts that work well without knowing the cache size, structures for persistent memory, and learned indexes (2018 onwards) that replace a B-tree's upper levels with a model of the key distribution. Whether learned indexes beat well-tuned classic structures in general is still debated.

What would change your mind? If memory latency stopped depending on distance, the cache-based argument for arrays would weaken and Big-O alone would decide between structures.

Recall

Why is appending to a dynamic array amortised O(1)?

Doubling makes the total copying a geometric series below 2n, so the average cost per append is constant.

When should you choose a balanced tree over a hash table?

When you need ordered iteration, range queries or a guaranteed O(log n) worst case.

Why do arrays beat linked lists more often than Big-O suggests?

Caches load memory in lines and prefetch ahead, so contiguous data is far cheaper to scan than scattered nodes.

How do languages defend hash tables against chosen keys?

A random per-process hash seed, or tree-shaped buckets with an O(log n) worst case.

What does every data structure keep valid between operations?

An invariant, such as sorted order, a balance rule or the heap order.

Reflect

Be honest with yourself; this stays in your browser. Anything you can't tick yet is what to revisit.