Skip to lesson

A hash table provides near-instantaneous key lookups. It converts arbitrary keys into array indices using a mathematical hash function.

From key to index with a hash function

A hash function turns a key into an integer called its hash code; the same key always gives the same hash code, and good functions spread keys evenly.

A hash table turns a key into an array position. A hash function converts the key into an integer, and the remainder after dividing by the capacity gives a valid bucket index.

  1. Compute the integer hash code of the input key.
  2. Apply modulo capacity to map the code into array bounds.
  3. Handle negative integers to guarantee a non-negative index.
  4. Use the computed index to access the target slot.

Example 1 · Computing Bucket Indices for String Keys

SimpleHashDemo.javaJava
public class SimpleHashDemo {    public static int getBucketIndex(String key, int capacity) {        int hash = 0;        for (char ch : key.toCharArray()) {            hash = 31 * hash + ch;        }        int index = hash % capacity;        if (index < 0) {            index += capacity;        }        return index;    }
    public static void main(String[] args) {        int capacity = 10;        String[] keys = {"order", "ticket", "invoice"};        for (String k : keys) {            System.out.println(k + " -> " + getBucketIndex(k, capacity));        }    }}
Output
order -> 0
ticket -> 8
invoice -> 7

What this code does

  • Polynomial rolling hash accumulates characters multiplied by prime 31.
  • Modulo capacity maps the large integer code to range 0 through 9.
  • Negative hash codes are shifted by capacity to guarantee positive indices.

Example 2 · Safe Modulo Formula for Negative Hash Codes

SafeModuloDemo.javaJava
public class SafeModuloDemo {    public static int safeIndex(int hashCode, int capacity) {        int idx = hashCode % capacity;        if (idx < 0) idx += capacity;        return idx;    }
    public static void main(String[] args) {        int cap = 10;        int h1 = 25;        int h2 = -17;        int h3 = Integer.MIN_VALUE; // -2147483648        System.out.println("25 -> " + safeIndex(h1, cap));        System.out.println("-17 -> " + safeIndex(h2, cap));        System.out.println("MIN -> " + safeIndex(h3, cap));    }}
Output
25 -> 5
-17 -> 3
MIN -> 2

What this code does

  • Positive hash 25 maps to index 5 via 25 % 10.
  • Negative hash -17 yields remainder -7; adding capacity 10 gives index 3.
  • Integer.MIN_VALUE has remainder -8; adding 10 yields safe positive index 2.

Arrays allow instant index lookups, but keys are often strings or large numbers. Why not store entries in an unsorted list? Searching an unsorted list requires scanning every element in O(n) time. A sorted array allows O(log n) binary search, but inserting new entries takes O(n) shifts. A hash function bridges the gap by converting arbitrary keys into integer codes. Modulo arithmetic then compresses this integer into a valid array slot index. Negative hash codes must be converted to positive values before applying modulo. Let capacity be 10. Key 'order' has hash code 106006350. 106006350 % 10 = 0, placing 'order' in bucket 0. Key 'ticket' has negative hash code -873960692. Its remainder is -2, and adding the capacity gives the valid index 8. Both keys map to valid array slots in constant O(1) time.

  • Hash function: a deterministic function converting arbitrary data into an integer.
  • Deterministic rule: identical keys must always produce identical integer codes.
  • Slot compression: index = (hashCode % capacity + capacity) % capacity.

Order of execution

From key to bucket index

Tap the steps in the order the code runs them.

int hash = key.hashCode();
int index = hash % capacity;
if (index < 0) {
index += capacity;
}

Buckets and collision reality

A collision happens when two different keys produce the same bucket index, so both entries must share one bucket.

Each slot of the backing array is called a bucket. Two different keys can land in the same bucket, which is called a collision. The example below makes one happen.

Example 3 · Demonstrating a Hash Collision

HashCollisionDemo.javaJava
public class HashCollisionDemo {    public static int simpleHash(String key, int capacity) {        int sum = 0;        for (char c : key.toCharArray()) {            sum += c;        }        return sum % capacity;    }
    public static void main(String[] args) {        int capacity = 5;        // 'ab' is 97 + 98 = 195. 195 % 5 = 0        // 'ba' is 98 + 97 = 195. 195 % 5 = 0        int idx1 = simpleHash("ab", capacity);        int idx2 = simpleHash("ba", capacity);        System.out.println("ab: " + idx1);        System.out.println("ba: " + idx2);        System.out.println("Collision: " + (idx1 == idx2));    }}
Output
ab: 0
ba: 0
Collision: true

What this code does

  • Both strings have identical character sums of 195.
  • Modulo 5 yields bucket index 0 for both keys.
  • This proves order-independent sum hashing suffers frequent collisions.

Collisions are inevitable because infinite possible keys map into a finite array capacity. A good hash function distributes keys uniformly across all available buckets.

  • Bucket: an individual storage location within the hash table array.
  • Collision: when two different keys map to the identical bucket index.
  • Uniform distribution: spreading entries evenly to minimize clustering.

Predict the output

Predict the bucket

Read each snippet and pick what it prints.

Round 1 of 2

int capacity = 5;
int a = ("ab".charAt(0) + "ab".charAt(1)) % capacity;
int b = ("ba".charAt(0) + "ba".charAt(1)) % capacity;
System.out.println(a + " " + b);

Why lookup is O(1) on average

Computing a hash code and array index takes constant O(1) time.

When collisions are few, searching inside a bucket takes constant time on average.

If all keys collide into one single bucket, search degrades to linear O(n) time. Proper sizing and good hash functions keep average lookup cost at O(1).

  • Average case: O(1) lookup when keys distribute evenly across buckets.
  • Worst case: O(n) lookup when all keys collide into one bucket.
  • Space-time trade-off: uses extra memory to achieve constant time operations.

Next step

Check your understanding

10 quick questions