Skip to content
Codescope

Hash tables

A hash becomes a bucket index, and average O(1) lookup follows.

core9 min6 steps

Before you start

A **hash table** answers "look up a value by any key" in constant time. Python's dict, JavaScript's object, Java's HashMap — all the same idea underneath.

The trick: convert the key into a number (a **hash**), reduce that number to an index into an array of **buckets**, and store the entry there. Going back is the same process, so lookup is one calculation and one memory read.

This lesson shows keys landing in buckets, then shows what happens when two keys hash to the same bucket — a **collision** — and how the table handles it by keeping a small chain per bucket.

Hash table (size 8)

hash(key) % size → bucket index
[0]
—
[1]
—
[2]
—
[3]
—
[4]
—
[5]
—
[6]
—
[7]
—

8 buckets, all empty. The hash function decides which bucket a key goes into.

Step 1 of 6. An array of empty buckets. A hash table starts as an array of buckets — here, 8 of them. Each bucket can hold a chain of key-value pairs. The hash function maps any key to an index 0..7. If the function distributes keys evenly, most buckets hold 0 or 1 entries, and lookup is O(1).

01 / 06

Step 01 / 06

An array of empty buckets

A hash table starts as an array of buckets — here, 8 of them. Each bucket can hold a chain of key-value pairs.

The hash function maps any key to an index 0..7. If the function distributes keys evenly, most buckets hold 0 or 1 entries, and lookup is O(1).

hash-tables.cC
// Simplified hash table with chaining#define SIZE 8int hash(const char *key) {    int h = 0;    while (*key) h = h * 31 + *key++;    return h % SIZE;          // map to bucket 0..7}void put(Table *t, const char *key, int val) {    int bucket = hash(key);    // insert at head of chain in t->buckets[bucket]}int get(Table *t, const char *key) {    int bucket = hash(key);    // walk the chain, compare keys    // average O(1), worst O(n)}// Example insertions:// hash("cat") % 8 = 3// hash("dog") % 8 = 6// hash("ant") % 8 = 3  ← collision with "cat"