Direct-Address Tables
Suppose every key is an integer from a small universe , and no two elements have the same key. Then the fastest possible dictionary is an array in which slot holds the element with key , 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
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] = NILEach is 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).
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.
#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 stored keys out of a universe of size , the space is while only slots do anything. That is fine for room numbers, ASCII characters or the vertices of a graph. It is impossible for 64-bit integers (), for strings, or for anything that is not a small integer to begin with.
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 proportional to the number of stored keys, not to . A hash function maps each key to a slot. Because , 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 so that they are rare (hash functions, universal hashing). Even with a random , collisions appear much earlier than intuition suggests: with slots, the first collision is expected after only about keys, the birthday paradox.
Test yourself
A direct-address table stores 1000 keys from the universe . How many slots does it have?
- 1000
- about 2000
What is the worst-case time of DIRECT-SEARCH?
- expected, worst
Why must a hash function from a universe of size to slots have collisions?
- Because it is random
- By the pigeonhole principle: more keys than slots means two keys share a slot
- Only if the table is full
- It need not; a good hash function has none