TExcelTAD
Home › Data Structures: Hashing, Search Trees, B-Trees & Union-Find › Data Structures: What This Course Covers

Data Structures: What This Course Covers

An algorithm rarely works on raw data. It keeps a set of items that grows, shrinks and is questioned while the algorithm runs: the vertices still to visit, the words seen so far, the open intervals, the groups that have merged. How fast the algorithm runs then depends on how that set is stored. This course studies the classic ways to store such a dynamic set and proves what each one costs.

The Data Structures and Algorithms course introduces lists, hash tables and trees by example, and Sorting & Order Statistics already analysed one structure, the binary heap. Here every structure gets a precise definition, an invariant, a proof of its running time and a program that checks the invariant on thousands of random inputs.

Dynamic sets and their operations

A dynamic set holds elements, each identified by a key, usually with satellite data attached (a record, a pointer, a value). The operations fall into two groups.

Kind Operation Meaning
query SEARCH(S,k)(S, k) return an element with key kk, or nothing
query MINIMUM(S)(S), MAXIMUM(S)(S) the element with the smallest or largest key
query SUCCESSOR(S,x)(S, x), PREDECESSOR(S,x)(S, x) the next larger or next smaller element after xx
modifying INSERT(S,x)(S, x) add element xx
modifying DELETE(S,x)(S, x) remove element xx (given the element itself, not just its key)

Not every structure supports every operation well. A hash table answers SEARCH in expected constant time but knows nothing about order, so MINIMUM or SUCCESSOR cost a full scan. A balanced search tree answers all of them in O(lg⁡n)O(\lg n). Choosing a structure means choosing which operations must be fast.

A first comparison: three ways to store a set

The program stores the same random keys three ways and counts key comparisons for 2000 inserts followed by 2000 searches: an unsorted list (insert at the end, search by scanning), a sorted list (binary search, but inserting must shift elements, which the program counts as moves), and an unbalanced binary search tree.

python · try it yourself
import random

def unsorted_list(keys, queries):
    a, comps = [], 0
    for k in keys:
        a.append(k)
    for q in queries:
        for x in a:
            comps += 1
            if x == q:
                break
    return comps, 0

def sorted_list(keys, queries):
    a, comps, moves = [], 0, 0
    def lower_bound(q):
        nonlocal comps
        lo, hi = 0, len(a)
        while lo < hi:
            mid = (lo + hi) // 2
            comps += 1
            if a[mid] < q: lo = mid + 1
            else: hi = mid
        return lo
    for k in keys:
        i = lower_bound(k)
        moves += len(a) - i            # elements shifted right by one
        a.insert(i, k)
    for q in queries:
        lower_bound(q)
    return comps, moves

def bst(keys, queries):
    root, comps = None, 0              # a node is [key, left, right]
    for k in keys:
        if root is None:
            root = [k, None, None]; continue
        x = root
        while True:
            comps += 1
            side = 1 if k < x[0] else 2
            if x[side] is None:
                x[side] = [k, None, None]; break
            x = x[side]
    for q in queries:
        x = root
        while x is not None:
            comps += 1
            if q == x[0]: break
            x = x[1] if q < x[0] else x[2]
    return comps, 0

rng = random.Random(7)
keys = rng.sample(range(1_000_000), 2000)
queries = [rng.choice(keys) for _ in range(2000)]
for f in [unsorted_list, sorted_list, bst]:
    c, m = f(keys, queries)
    print(f"{f.__name__:>13}: {c:>9,} comparisons, {m:>9,} element moves")
unsorted_list: 1,994,691 comparisons,         0 element moves
  sorted_list:    41,115 comparisons,   993,587 element moves
          bst:    49,414 comparisons,         0 element moves

The unsorted list pays about n/2n/2 comparisons per search, the quadratic total. The sorted list searches in lg⁡n\lg n comparisons but pays a quadratic number of moves for its inserts. The search tree does both in about a dozen comparisons per operation, because the keys arrived in random order: a random tree on 2000 keys has an average node depth of 2(1+1/n)Hn−4≈12.42(1 + 1/n)H_n - 4 \approx 12.4 (The Expected Height of a Random BST). On sorted input the same tree degenerates into a path; the red-black trees of this course prevent that for every input.

Which questions a structure can answer cheaply

Python's built-in dict is a hash table, and a sorted list with the bisect module is a sorted array. The program wraps the keys in a class that counts every comparison (== for the hash table, < for binary search) and asks each structure three questions: is a key present, what is the next larger key, and what is the median.

python · try it yourself
import bisect, random

class Key:
    count = 0
    def __init__(self, v): self.v = v
    def __hash__(self): return hash(self.v)
    def __eq__(self, other): Key.count += 1; return self.v == other.v
    def __lt__(self, other): Key.count += 1; return self.v < other.v

rng = random.Random(3)
values = rng.sample(range(10 ** 6), 10000)
table = {Key(v): None for v in values}            # hash table
ordered = sorted(Key(v) for v in values)          # sorted array
q = Key(values[1234])

def cost(f):
    Key.count = 0
    result = f()
    return result, Key.count

print("membership, dict:       ", cost(lambda: q in table))
print("membership, sorted list:", cost(lambda: ordered[bisect.bisect_left(ordered, q)].v == q.v))
print("next larger, dict:      ", cost(lambda: min((k for k in table if q < k), key=lambda k: k.v).v))
print("next larger, sorted:    ", cost(lambda: ordered[bisect.bisect_right(ordered, q)].v))
print("median, dict:           ", cost(lambda: sorted(table)[len(table) // 2].v))
print("median, sorted list:    ", cost(lambda: ordered[len(ordered) // 2].v))
membership, dict:        (True, 1)
membership, sorted list: (True, 13)
next larger, dict:       (505330, 10000)
next larger, sorted:     (505330, 13)
median, dict:            (489609, 120223)
median, sorted list:     (489609, 0)

The hash table answers membership with a single key comparison, but "next larger" and "median" force it to look at every key, or to sort them all. The sorted list answers order questions in about lg⁡n≈13\lg n \approx 13 comparisons or none at all, but, as the first program showed, pays for it on every insertion. Balanced search trees and their augmented versions sit in between: O(lg⁡n)O(\lg n) for all of these questions and for updates.

What the course covers

Section Structures Main results
Elementary data structures dynamic arrays, stacks, queues, linked lists, rooted trees doubling gives amortized O(1)O(1) appends; O(1)O(1) stack, queue and list operations
Hash tables direct addressing, chaining, open addressing expected Θ(1+α)\Theta(1 + \alpha) with chaining; at most 1/(1−α)1/(1-\alpha) probes with open addressing; universal hashing works for every input
Binary search trees search, minimum, successor, insert, delete every operation is O(h)O(h); a randomly built tree has expected height O(lg⁡n)O(\lg n)
Red-black trees rotations, insertion and deletion fix-ups height at most 2lg⁡(n+1)2 \lg(n+1), so every operation is O(lg⁡n)O(\lg n) in the worst case
Augmenting data structures order-statistic trees, interval trees SELECT and RANK in O(lg⁡n)O(\lg n); overlap queries in O(lg⁡n)O(\lg n)
B-trees search, insert, delete height at most log⁡tn+12\log_t \frac{n+1}{2}; O(log⁡tn)O(\log_t n) disk reads per operation
Disjoint sets linked lists, forests, union by rank, path compression mm operations in O(m α(n))O(m \, \alpha(n)) time, where α\alpha grows slower than any iterated logarithm

Conventions

  • As in the earlier courses, arrays are 0-based, slices are half-open, lg⁡n=log⁡2n\lg n = \log_2 n, and pseudocode is in the style described in How to read pseudocode.
  • Trees are built from small node objects with key, left, right and parent fields. Python examples use classes with __slots__; the C++ versions use structs, and for the larger trees indices into a std::vector instead of raw pointers, which keeps them short and free of leaks.
  • Every tree lesson checks its invariants with assert after each operation, on many seeded random inputs, so a run that prints its summary line is evidence that the code is correct, not only that it ran.
  • Costs are counted, never timed: comparisons, probes, rotations, disk reads. Random choices use a fixed seed, so you get exactly the output shown.

The structures are where many standard library types come from, and the lessons point out the connection: Python's list is a dynamic array and dict an open-addressing hash table; C++'s std::vector is a dynamic array, std::unordered_map a chained hash table and std::map a red-black tree in the common implementations. The practice area has problems for several lessons: Linear Probing Table, Components After Each Union, Maximum Overlap of Intervals and LRU Cache, among others.

Test yourself

Which operation does a hash table support poorly compared with a balanced search tree?

  1. SEARCH by key
  2. INSERT
  3. SUCCESSOR (the next larger key)
  4. DELETE of a given element

Why did the sorted list in the first example make about a million element moves?

  1. Binary search is slow
  2. Each insert shifts all larger elements one place to the right, about n/2n/2 on average
  3. Python lists are linked lists
  4. The list was re-sorted after every insert

DELETE(S,x)(S, x) in this course takes...

  1. a key, which it must search for first
  2. the element xx itself (a pointer to it), so no search is needed
  3. the position of xx in sorted order
  4. nothing: it removes the minimum