The whole, before the parts

A data structure is a choice about how to arrange data in memory, and the one idea that carries the subject is that this choice is a trade: every arrangement makes some operations cheap by making others expensive. There is no best structure, only a best structure for the operations you will actually perform. Learning the catalogue below is really learning to ask one question first — what will this data be asked to do most often? — and to read each structure as an answer to it. Citation needed

Terminology and core concepts

  1. Cost vocabulary

    Costs are named by how they grow with the number of items n: constant time does not grow at all, logarithmic time grows like the number of halvings of n, and linear time grows in proportion to n. Citation needed

    What happens to a constant-time operation as the data doubles?
    nothing — its cost stays the same Citation needed
    What happens to a logarithmic cost when n doubles?
    it grows by one step Citation needed
    What happens to a linear cost when n doubles?
    it doubles Citation needed
    Roughly how many halvings take 1,000,000 down to 1?
    about 20 Citation needed
    Which grows slower for large n: logarithmic or linear?
    logarithmic, by an enormous margin Citation needed
  2. The array

    An array stores items in one contiguous block, so the address of item i is computable by arithmetic — which makes access by position constant time, and insertion in the middle linear time, because everything after the gap must shift. Citation needed

    Why is array access by index constant time?
    the address is computed by arithmetic, not search Citation needed
    Why is inserting at the front of an array linear time?
    every existing item must shift one place Citation needed
    What does contiguous storage cost you?
    cheap insertion and growth Citation needed
    What is the address of item i given base b and item size s?
    b + i × s Citation needed
  3. The linked list

    A linked list stores each item in its own node — a record holding the item plus a pointer, the address of the next node — so insertion anywhere you already stand is constant time, but reaching position i means walking i pointers. Citation needed

    What is a pointer?
    a stored address of another piece of data Citation needed
    Why is linked-list insertion at a known node constant time?
    only two pointers change; nothing shifts Citation needed
    Why is access by position linear in a linked list?
    you must walk the pointers one by one Citation needed
    Which wins for random access by index: array or linked list?
    array Citation needed
    Which wins for splicing an item into the middle, position in hand?
    linked list Citation needed
  4. Stack and queue

    A stack and a queue restrict access on purpose: a stack serves the most recently added item first (last in, first out), a queue the oldest first (first in, first out) — and the restriction is the feature, because it matches how nesting and waiting actually behave. Citation needed

    Which item does a stack serve next?
    the most recently added one Citation needed
    Which item does a queue serve next?
    the oldest one still waiting Citation needed
    Why does a stack match nested procedure calls?
    the call entered last must finish first Citation needed
    What structure keeps tasks in arrival order?
    a queue Citation needed
    What do you get by pushing a sequence onto a stack and popping it all?
    the sequence reversed Citation needed
  5. The hash table

    A hash table finds items by computing where they should be: a hash function maps each key to an array position, giving constant-time lookup on average — degraded only by collisions, two keys sent to the same position, which must be resolved and multiply as the table fills. Citation needed

    How does a hash table locate a key?
    computes its position with the hash function Citation needed
    What is a collision?
    two keys hashed to the same position Citation needed
    Why do lookups slow as a hash table fills?
    collisions multiply, lengthening each probe Citation needed
    What is the average-case cost of hash lookup?
    constant time Citation needed
    What can a hash table not do that a sorted structure can?
    serve keys in order Citation needed
  6. Trees and binary search trees

    A tree is nodes linked by pointers with one root and no cycles; a binary search tree additionally keeps everything smaller to a node's left and larger to its right, so each comparison discards half the remaining tree — logarithmic search, if the tree stays balanced. Citation needed

    What ordering rule defines a binary search tree?
    smaller keys left of a node, larger keys right Citation needed
    Why is balanced search logarithmic?
    each comparison discards half the tree Citation needed
    What happens to search cost when a tree degenerates into a chain?
    it becomes linear Citation needed
    What produces a degenerate tree?
    inserting keys in sorted order, unrebalanced Citation needed
    What do self-balancing trees guarantee that plain ones do not?
    logarithmic height regardless of insertion order Citation needed
  7. The heap

    A heap is a tree that keeps only one promise — every node beats its children — which is weaker than full sorted order and exactly cheap enough to serve the current minimum (or maximum) fast; it is the structure behind the priority queue, which serves the most urgent item rather than the oldest. Citation needed

    What single invariant does a min-heap maintain?
    each node is no larger than its children Citation needed
    Where does a min-heap keep its smallest item?
    at the root Citation needed
    What does a priority queue serve next?
    the most urgent item, not the oldest Citation needed
    Why not keep a priority queue fully sorted?
    the heap's weaker promise is cheaper and suffices Citation needed
    What is the cost of removing the minimum from a heap of n items?
    logarithmic time Citation needed
  8. Graphs and their two representations

    A graph is a set of vertices joined by edges, and it is stored either as an adjacency matrix — a grid answering "is there an edge?" in constant time at quadratic space — or as adjacency lists — per-vertex lists of neighbours, paying only for edges that exist. Citation needed

    What does an adjacency matrix answer in constant time?
    whether an edge joins two given vertices Citation needed
    What space does an adjacency matrix take for V vertices?
    V² entries, edges or not Citation needed
    What does an adjacency list store per vertex?
    only its actual neighbours Citation needed
    Which representation suits a sparse graph?
    adjacency lists Citation needed
    Which is cheaper for "visit all neighbours of v" in a sparse graph?
    the adjacency list Citation needed
  9. Amortized cost and the dynamic array

    Some structures pay for rare expensive operations with many cheap ones; amortized cost is the average over the whole sequence — the dynamic array doubles its block when full, and that occasional linear copy averages out to constant time per append. Citation needed

    What does amortized cost average over?
    a whole sequence of operations, not one Citation needed
    What does a dynamic array do when its block is full?
    allocates double the space and copies everything Citation needed
    What is the amortized cost of one append?
    constant time Citation needed
    Why double rather than grow by a fixed amount?
    fixed growth forces copies too often, making appends linear Citation needed

Problems that prove it

  1. Insert the keys 50, 30, 70, 20, 40, 60, 80 into an empty binary search tree, then find 40.

    Drills: the ordering invariant doing the navigating.

    Derivation steps
    1. 50 becomes the root.
    2. 30 < 50: left child of 50. 70 > 50: right child of 50.
    3. 20 < 50, < 30: left of 30. 40 < 50, > 30: right of 30.
    4. 60 > 50, < 70: left of 70. 80 > 50, > 70: right of 70.
    5. Find 40: at 50 go left (40 < 50), at 30 go right (40 > 30), found. Three comparisons for seven keys — the halving at work.

    Citation needed

  2. Insert the same seven keys in sorted order — 20, 30, 40, 50, 60, 70, 80 — and count the comparisons to find 80.

    Drills: how insertion order degrades an unbalanced tree to a chain.

    Derivation steps
    1. 20 is the root; every later key is larger than everything so far.
    2. Each key becomes the right child of the previous one: a chain of seven nodes.
    3. Finding 80 walks all seven nodes: seven comparisons, versus three in the balanced tree.
    4. Same keys, same structure type, linear instead of logarithmic — which is the case for self-balancing trees.

    Citation needed

  3. A dynamic array starts with capacity 1 and doubles when full. Count the total copies made while appending 32 items.

    Drills: the amortized argument as an actual count.

    Derivation steps
    1. Doublings happen at sizes 1, 2, 4, 8, 16 — copying 1, 2, 4, 8, 16 items respectively.
    2. Total copies: 1 + 2 + 4 + 8 + 16 = 31.
    3. So 32 appends cost 32 writes + 31 copies = 63 operations.
    4. Per append: 63/32 < 2 — constant amortized cost, despite the 16-item copy near the end.

    Citation needed

  4. You must check whether a long string of brackets — like ([{}]()) — is properly nested. Pick the structure and run it on ([)].

    Drills: matching a structure's access discipline to the problem's shape.

    Derivation steps
    1. Nesting means the most recently opened bracket must close first: last in, first out — a stack.
    2. Rule: push every opener; on a closer, pop and demand it matches.
    3. Run on ([)]: push ( ; push [ ; see ) and pop [ — mismatch.
    4. Verdict: improperly nested, detected at the third symbol without reading the rest.

    Citation needed

Sources

  • Thomas Cormen, Charles Leiserson, Ronald Rivest, and Clifford Stein, Introduction to Algorithms — the standard reference for every structure here and its costs.
  • Robert Sedgewick and Kevin Wayne, Algorithms — the same catalogue with working code and empirical measurement.
  • Jon Bentley, Programming Pearls — choosing representations from the operations actually needed.

Learning path

Continue through Computer Science in order, using the concepts above to connect this topic to the next.