TExcelTAD

Direct-Address Tables

Suppose every key is an integer from a small universe U={0,1,…,m−1}U = \{0, 1, \ldots, m - 1\}, and no two elements have the same key. Then the fastest possible dictionary is an array T[0:m]T[0:m] in which slot kk holds the element with key kk, or NIL if there is none. That is a direct-address table, and SEARCH, INSERT and DELETE each take one array access.

Hash tables are what you get when you want the same speed but the universe is far too large for an array with one slot per possible key. This short lesson sets up the baseline and the problem that hashing solves.

The operations

text
DIRECT-SEARCH(T, k)        DIRECT-INSERT(T, x)        DIRECT-DELETE(T, x)
1  return T[k]             1  T[x.key] = x            1  T[x.key] = NIL

Each is O(1)O(1) in the worst case, with no assumptions about the keys beyond their range. The table can store the element itself in the slot, or a pointer to it; if only the set of keys matters, a single bit per slot is enough (a bit vector).

python · try it yourself
class DirectTable:
    def __init__(self, m):
        self.slots = [None] * m
    def insert(self, key, value):
        self.slots[key] = (key, value)
    def search(self, key):
        return self.slots[key]
    def delete(self, key):
        self.slots[key] = None

rooms = DirectTable(500)                    # hotel rooms 0..499
rooms.insert(101, "Ana")
rooms.insert(342, "Bo")
rooms.insert(17, "Cy")
rooms.delete(342)
for r in [17, 101, 342, 499]:
    print(f"room {r}: {rooms.search(r)}")
print("slots in use:", sum(s is not None for s in rooms.slots), "of", len(rooms.slots))
room 17: (17, 'Cy')
room 101: (101, 'Ana')
room 342: None
room 499: None
slots in use: 2 of 500

In C++

When only membership matters, std::bitset gives a bit vector with a compile-time size, and std::vector<bool> one with a run-time size. The program marks the primes below 10,000 in a bit vector with the sieve of Eratosthenes, then answers membership queries with one bit test each.

cpp · try it yourself
#include <bitset>
#include <cstdio>

int main() {
    constexpr int M = 10000;
    std::bitset<M> composite;                    // direct addressing on keys 0..M-1, one bit each
    composite[0] = composite[1] = true;
    for (int p = 2; p * p < M; ++p)
        if (!composite[p])
            for (int q = p * p; q < M; q += p) composite[q] = true;

    std::printf("primes below %d: %zu\n", M, M - composite.count());
    for (int k : {97, 1001, 7919, 9999}) std::printf("%d is %s\n", k, composite[k] ? "not prime" : "prime");
    std::printf("table size: %zu bytes for %d keys\n", sizeof(composite), M);
}
primes below 10000: 1229
97 is prime
1001 is not prime
7919 is prime
9999 is not prime
table size: 1256 bytes for 10000 keys

When direct addressing breaks down

The table has one slot per possible key, whether or not it is used. With nn stored keys out of a universe of size ∣U∣\lvert U \rvert, the space is Θ(∣U∣)\Theta(\lvert U \rvert) while only nn slots do anything. That is fine for room numbers, ASCII characters or the vertices 0..n−10..n-1 of a graph. It is impossible for 64-bit integers (∣U∣=264\lvert U \rvert = 2^{64}), for strings, or for anything that is not a small integer to begin with.

python · try it yourself
universes = [
    ("ASCII characters", 2 ** 7),
    ("16-bit port numbers", 2 ** 16),
    ("32-bit IPv4 addresses", 2 ** 32),
    ("64-bit integers", 2 ** 64),
    ("strings of 10 lowercase letters", 26 ** 10),
]
n = 1_000_000                                      # keys actually stored
for name, size in universes:
    table_bytes = size // 8                        # even as a bit vector
    use = min(1.0, n / size)
    print(f"{name:32} |U| = {size:.3g}  bit vector {table_bytes:.3g} bytes, fraction used {use:.2g}")
ASCII characters                 |U| = 128  bit vector 16 bytes, fraction used 1
16-bit port numbers              |U| = 6.55e+04  bit vector 8.19e+03 bytes, fraction used 1
32-bit IPv4 addresses            |U| = 4.29e+09  bit vector 5.37e+08 bytes, fraction used 0.00023
64-bit integers                  |U| = 1.84e+19  bit vector 2.31e+18 bytes, fraction used 5.4e-14
strings of 10 lowercase letters  |U| = 1.41e+14  bit vector 1.76e+13 bytes, fraction used 7.1e-09

(For the two small universes a million keys cannot all be distinct; the fraction is capped at 1.) A bit vector for IPv4 addresses still fits in half a gigabyte, but anything beyond that does not fit in any memory.

Hashing keeps the idea of computing a slot from the key, but uses a table of size mm proportional to the number nn of stored keys, not to ∣U∣\lvert U \rvert. A hash function h:U→{0,…,m−1}h : U \to \{0, \ldots, m - 1\} maps each key to a slot. Because ∣U∣>m\lvert U \rvert > m, by the pigeonhole principle some keys must share a slot, a collision, and the next lessons are about handling collisions (chaining and open addressing) and choosing hh so that they are rare (hash functions, universal hashing). Even with a random hh, collisions appear much earlier than intuition suggests: with mm slots, the first collision is expected after only about πm/2\sqrt{\pi m / 2} keys, the birthday paradox.

Test yourself

A direct-address table stores 1000 keys from the universe {0,…,106−1}\{0, \ldots, 10^6 - 1\}. How many slots does it have?

  1. 1000
  2. about 2000
  3. 10610^6
  4. 106=1000\sqrt{10^6} = 1000

What is the worst-case time of DIRECT-SEARCH?

  1. O(1)O(1)
  2. O(lg⁡m)O(\lg m)
  3. O(n)O(n)
  4. O(1)O(1) expected, O(n)O(n) worst

Why must a hash function from a universe of size ∣U∣>m\lvert U \rvert > m to mm slots have collisions?

  1. Because it is random
  2. By the pigeonhole principle: more keys than slots means two keys share a slot
  3. Only if the table is full
  4. It need not; a good hash function has none