Data structures

12 structures, each on one reference page: what it is, its operations and their complexity, the invariants it keeps, when to use it and when not to, the built-in equivalents in C#, Python, Java and C++, and an implementation tested in all four languages. The lessons go deeper.

Linear structures

  • Fixed-capacity array

    A block of equal-sized slots that never grows: O(1) access by computed address, O(n) insert and delete by shifting, and an error when full.

    Get / set by index O(1) · Append O(1)

  • Dynamic array

    A contiguous buffer that grows by reallocating: constant-time indexing, amortized constant-time append, linear-time insert and remove in the middle.

    Get / set by index O(1) · Append O(1) amortized

  • Linked list

    Nodes that point to the next node: constant-time insertion at a known position, but no indexing and poor cache locality.

    Prepend O(1) · Append (with a tail reference) O(1)

  • Stack

    Last in, first out: push and pop at one end in amortized O(1). The model behind call stacks, undo histories and bracket matching.

    Push O(1) amortized · Pop O(1)

  • Queue and deque

    First in, first out. A ring buffer gives O(1) enqueue and dequeue without shifting; a deque adds both ends.

    Enqueue O(1) · Dequeue O(1)

Hashing

  • Hash table

    Keys hashed to buckets: expected O(1) insert, lookup and delete, as long as the hash spreads keys and the load factor stays bounded.

    Put O(1) expected, amortized · Get O(1) expected

Trees and heaps

  • Binary heap

    A complete binary tree stored in an array, ordered so the smallest (or largest) element is at the root: the standard priority queue.

    Peek min O(1) · Push O(log n)

  • Binary search tree

    A binary tree ordered so that an inorder walk is sorted: search, insert and delete in O(h), which is O(log n) only while the tree stays balanced.

    Search O(h) · Insert O(h)

  • AVL tree

    A binary search tree that rebalances with rotations so the heights of every node’s subtrees differ by at most one: O(log n) search and insert.

    Search O(log n) · Insert O(log n)

  • Trie

    A tree of characters where each path from the root spells a prefix: insert, lookup and prefix queries in O(L) for a word of length L.

    Insert word O(L) · Search word O(L)

Graphs and disjoint sets

  • Union-find

    Disjoint sets as a forest of parent pointers: union and find in near-constant amortized time with union by rank and path compression.

    Make set O(1) · Find O(α(n)) amortized

  • Graph

    Vertices joined by edges, stored as adjacency lists or a matrix. The representation decides how fast you can list neighbours or test an edge.

    Add edge O(1) · List neighbours of v O(deg v)

Looking for the procedures that run on these structures? See the algorithms. For every method of the standard library types, see the collections encyclopedia.