Hash Tables Explained: How They Work and Why Lookups Are O(1)

Learn how hash tables work: hash functions, buckets, load factor, resizing, and the hashCode contract, with runnable Python and Java code you can test.

Executive Summary: Below, I show how hash tables work from the inside. A hash function turns a key into an array index, colliding keys share a bucket, and the table doubles before it gets crowded. That design gives O(1) average-case lookups and inserts, but the worst case is O(n), and the guarantee holds only when the hash spreads keys well.
Diagram showing how hash tables work: a key passes through a hash function to a bucket index in an array of buckets

Picture a candidate checking whether each of 100,000 user IDs appears in a list of 100,000 banned IDs. The code is correct, and it times out. Each in check on a list scans every element, so the whole job does about 10^10 comparisons. Changing one line, from a list to a set, makes it finish almost instantly. That one line is a hash table at work.

A hash table is an array of slots, called buckets, plus a hash function that maps any key to one of those slots. Understanding how hash tables work means understanding three moving parts: the hash function, the collision strategy, and the resizing policy. Python’s dict and set and Java’s HashMap and HashSet are all hash tables, so this structure sits under a large share of the code you write.

The code assumes Python 3.12 and Java 21. Big-O notation describes how running time grows as input grows. Arrays give O(1) access by index because elements sit in one contiguous block; the guide to arrays and their O(1) indexing covers why.

My position: “hash lookups are O(1)” is not a fact, it is a contract with three clauses. The hash function must spread keys evenly, the table must resize before buckets get long, and a key must never change after you insert it. Break any clause and the constant quietly turns into a linear scan. Learn the contract and the code follows.

How to recognize when you need a hash table

Reach for a hash table when the problem asks “have I seen this before?” or “what do I know about this key?” Those two questions cover most interview uses.

  • Repeated membership tests. A list makes each check O(n); a set makes it O(1) on average.
  • Lookup by an identifier. You fetch a record by user ID, word, or coordinate pair, not by position.
  • Counting or grouping. You need how often each item occurs, or which items share a property.
  • A nested loop searching for a partner. An O(n^2) brute force usually collapses to O(n) with a map of what you have seen.

The applied versions, such as frequency counting and complement lookup, live in the guide to hash map patterns for frequency counting and Two Sum. Here I stay on the machine underneath them.

How hash tables work: from key to bucket

Every operation follows the same path. First, compute the key’s hash code, an integer derived from the key’s contents. Next, compress that integer into a valid index, usually with modulo or a bit mask. Finally, go to that bucket and compare keys for equality until you find a match or run out of entries.

 key "pear"
     |
     v
 hash("pear") = 3_948_201 (any int)
     |
     v
 index = hash % capacity = 3_948_201 % 8 = 1
     |
     v
 buckets (capacity 8)
 +-----+-----------------------------------+
 |  0  |  (empty)                          |
 |  1  |  ("apple", 3) -> ("pear", 5)       |  <- collision: two keys, one bucket
 |  2  |  (empty)                          |
 |  3  |  ("kiwi", 7)                      |
 |  4  |  (empty)                          |
 | ... |                                   |
 |  7  |  ("plum", 1)                      |
 +-----+-----------------------------------+
 size = 4, capacity = 8, load factor = 4 / 8 = 0.5

The hash code is the only part that depends on the key type. Integers often hash to themselves in Python, so hash(42) is 42. Java defines String.hashCode() as a polynomial in base 31 over the characters. The table itself does not care how the number was made. It only needs equal keys to produce equal numbers.

The equality check is the part people forget. Two different keys can land in the same bucket, so the table must confirm the match with == in Python or equals in Java. Production tables also store each entry’s full hash and compare it first, because integer comparison is cheaper than a full equality test.

Collisions are guaranteed, not unlucky

A collision happens when two different keys map to the same bucket. You cannot avoid collisions in general. There are far more possible strings than buckets, so by the pigeonhole principle some keys must share. In Java, "Aa" and "BB" both have hash code 2112, and they collide in every table size.

Tables handle collisions in one of two ways. Separate chaining keeps a small list in each bucket and appends colliding entries to it. Open addressing stores every entry directly in the array and probes other slots until it finds a free one. Java’s HashMap uses chaining, and CPython’s dict uses open addressing. The full comparison, including probing schemes, tombstones, and clustering, is in the guide to collision resolution: chaining vs open addressing.

Load factor and resizing

The load factor is the number of entries divided by the number of buckets. It predicts the average bucket length, which is the real cost of a lookup. Keep it bounded and a lookup touches a constant number of entries however large the table grows.

So every practical table resizes. Past a threshold, it allocates an array twice the size and reinserts every entry, since each index depends on the capacity. That rehash costs O(n), but it happens rarely.

The doubling argument shows why inserts stay cheap. After n inserts, all resizes together have moved at most n + n/2 + n/4 + … entries, which is less than 2n. Spread over n inserts, that is O(1) amortized per insert. Amortized means averaged over a sequence of operations, which differs from the average case over random inputs.

  • Java HashMap starts at 16 buckets with a load factor of 0.75, so the 13th insert triggers the first doubling to 32. The OpenJDK HashMap source shows this in putVal and resize.
  • CPython dict starts with 8 slots and resizes at about two-thirds full, defined as USABLE_FRACTION in the CPython dictobject.c source. Open addressing needs more free slots, because a crowded array makes probe sequences long.

If you know the final size, presize the table. Java 19 added HashMap.newHashMap(int), which accounts for the load factor and skips every intermediate rehash.

Building a hash table from scratch

The fastest way to learn how hash tables work is to build one. The version below uses separate chaining, a 0.75 load factor, and doubling. It supports put, get, and remove, and it overwrites the value when a key already exists.

In Python:

from typing import Generic, Hashable, Iterator, Optional, TypeVar

K = TypeVar("K", bound=Hashable)
V = TypeVar("V")


class ChainedHashTable(Generic[K, V]):
    """A hash table that resolves collisions with a list per bucket."""

    def __init__(self, capacity: int = 8, max_load: float = 0.75) -> None:
        self._buckets: list[list[tuple[K, V]]] = [[] for _ in range(capacity)]
        self._size = 0
        self._max_load = max_load

    def _index(self, key: K, capacity: int) -> int:
        # Python's % always returns a non-negative result for a positive capacity.
        return hash(key) % capacity

    def put(self, key: K, value: V) -> None:
        bucket = self._buckets[self._index(key, len(self._buckets))]
        for i, (existing, _) in enumerate(bucket):
            if existing == key:
                bucket[i] = (key, value)  # overwrite, size unchanged
                return
        bucket.append((key, value))
        self._size += 1
        if self._size / len(self._buckets) > self._max_load:
            self._resize(2 * len(self._buckets))

    def get(self, key: K, default: Optional[V] = None) -> Optional[V]:
        bucket = self._buckets[self._index(key, len(self._buckets))]
        for existing, value in bucket:
            if existing == key:
                return value
        return default

    def remove(self, key: K) -> bool:
        bucket = self._buckets[self._index(key, len(self._buckets))]
        for i, (existing, _) in enumerate(bucket):
            if existing == key:
                bucket[i] = bucket[-1]  # swap with last, then pop: O(1)
                bucket.pop()
                self._size -= 1
                return True
        return False

    def _resize(self, new_capacity: int) -> None:
        new_buckets: list[list[tuple[K, V]]] = [[] for _ in range(new_capacity)]
        for bucket in self._buckets:
            for key, value in bucket:
                new_buckets[self._index(key, new_capacity)].append((key, value))
        self._buckets = new_buckets

    def __len__(self) -> int:
        return self._size

    def __contains__(self, key: object) -> bool:
        sentinel = object()
        return self.get(key, sentinel) is not sentinel  # type: ignore[arg-type]

    def capacity(self) -> int:
        return len(self._buckets)

    def keys(self) -> Iterator[K]:
        for bucket in self._buckets:
            for key, _ in bucket:
                yield key


if __name__ == "__main__":
    # Empty table
    t: ChainedHashTable[object, int] = ChainedHashTable(capacity=4)
    assert len(t) == 0 and t.get("missing") is None and "missing" not in t
    assert t.remove("missing") is False

    # Normal case
    t.put("apple", 3)
    t.put("pear", 5)
    assert t.get("apple") == 3 and t.get("pear") == 5 and len(t) == 2

    # Duplicate key overwrites instead of adding a second entry
    t.put("apple", 10)
    assert t.get("apple") == 10 and len(t) == 2

    # Edge case: colliding keys (5, 9, 13 share index 1 when capacity is 4)
    # plus a resize in the middle of the inserts
    c: ChainedHashTable[int, str] = ChainedHashTable(capacity=4)
    for k in (5, 9, 2, 13):
        c.put(k, f"v{k}")
    assert c.capacity() == 8  # 4 items / 4 buckets > 0.75 triggered doubling
    assert all(c.get(k) == f"v{k}" for k in (5, 9, 2, 13))
    assert c.remove(9) and 9 not in c and c.get(13) == "v13" and len(c) == 3

    # 1, 1.0 and True compare equal and hash equal, so they are one key
    m: ChainedHashTable[object, str] = ChainedHashTable()
    m.put(1, "int")
    m.put(1.0, "float")
    m.put(True, "bool")
    assert len(m) == 1 and m.get(1) == "bool"

    # Many inserts keep the load factor under the limit
    big: ChainedHashTable[int, int] = ChainedHashTable()
    for i in range(10_000):
        big.put(i, i * i)
    assert len(big) == 10_000 and big.get(9_999) == 9_999 ** 2
    assert len(big) / big.capacity() <= 0.75
    print("all tests passed")

The same table in Java. It uses Math.floorMod because hashCode() can be negative, and a plain % would then return a negative index:

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class ChainedHashTable<K, V> {

    static final class Entry<K, V> {
        final K key;
        V value;

        Entry(K key, V value) {
            this.key = key;
            this.value = value;
        }
    }

    private List<List<Entry<K, V>>> buckets;
    private int size;
    private final double maxLoad;

    public ChainedHashTable(int capacity, double maxLoad) {
        this.buckets = newBuckets(capacity);
        this.maxLoad = maxLoad;
    }

    private static <K, V> List<List<Entry<K, V>>> newBuckets(int capacity) {
        List<List<Entry<K, V>>> fresh = new ArrayList<>(capacity);
        for (int i = 0; i < capacity; i++) {
            fresh.add(new ArrayList<>());
        }
        return fresh;
    }

    private static int indexFor(Object key, int capacity) {
        // floorMod keeps the index non-negative when hashCode() is negative.
        return Math.floorMod(Objects.hashCode(key), capacity);
    }

    public void put(K key, V value) {
        List<Entry<K, V>> bucket = buckets.get(indexFor(key, buckets.size()));
        for (Entry<K, V> e : bucket) {
            if (Objects.equals(e.key, key)) {
                e.value = value; // overwrite, size unchanged
                return;
            }
        }
        bucket.add(new Entry<>(key, value));
        size++;
        if ((double) size / buckets.size() > maxLoad) {
            resize(2 * buckets.size());
        }
    }

    public V get(K key) {
        for (Entry<K, V> e : buckets.get(indexFor(key, buckets.size()))) {
            if (Objects.equals(e.key, key)) {
                return e.value;
            }
        }
        return null;
    }

    public boolean containsKey(K key) {
        for (Entry<K, V> e : buckets.get(indexFor(key, buckets.size()))) {
            if (Objects.equals(e.key, key)) {
                return true;
            }
        }
        return false;
    }

    public boolean remove(K key) {
        List<Entry<K, V>> bucket = buckets.get(indexFor(key, buckets.size()));
        for (int i = 0; i < bucket.size(); i++) {
            if (Objects.equals(bucket.get(i).key, key)) {
                bucket.set(i, bucket.get(bucket.size() - 1)); // swap with last
                bucket.remove(bucket.size() - 1);
                size--;
                return true;
            }
        }
        return false;
    }

    private void resize(int newCapacity) {
        List<List<Entry<K, V>>> fresh = newBuckets(newCapacity);
        for (List<Entry<K, V>> bucket : buckets) {
            for (Entry<K, V> e : bucket) {
                fresh.get(indexFor(e.key, newCapacity)).add(e);
            }
        }
        buckets = fresh;
    }

    public int size() {
        return size;
    }

    public int capacity() {
        return buckets.size();
    }

    private static void check(boolean condition, String message) {
        if (!condition) {
            throw new AssertionError(message);
        }
    }

    public static void main(String[] args) {
        // Empty table
        ChainedHashTable<String, Integer> t = new ChainedHashTable<>(4, 0.75);
        check(t.size() == 0 && t.get("missing") == null, "empty get");
        check(!t.remove("missing"), "empty remove");

        // Normal case
        t.put("apple", 3);
        t.put("pear", 5);
        check(t.get("apple") == 3 && t.get("pear") == 5 && t.size() == 2, "normal");

        // Duplicate key overwrites
        t.put("apple", 10);
        check(t.get("apple") == 10 && t.size() == 2, "duplicate overwrite");

        // Edge case: "Aa" and "BB" have the same String.hashCode() (2112)
        check("Aa".hashCode() == "BB".hashCode(), "known collision");
        t.put("Aa", 1);
        t.put("BB", 2);
        check(t.get("Aa") == 1 && t.get("BB") == 2, "colliding strings kept apart");

        // Collisions plus a resize: 5, 9, 13 share index 1 when capacity is 4
        ChainedHashTable<Integer, String> c = new ChainedHashTable<>(4, 0.75);
        int[] keys = {5, 9, 2, 13};
        for (int k : keys) {
            c.put(k, "v" + k);
        }
        check(c.capacity() == 8, "resize happened");
        for (int k : keys) {
            check(("v" + k).equals(c.get(k)), "lookup after resize " + k);
        }
        check(c.remove(9) && !c.containsKey(9) && "v13".equals(c.get(13)), "remove in chain");

        // Negative hash codes must not produce a negative index
        ChainedHashTable<Integer, Integer> neg = new ChainedHashTable<>(8, 0.75);
        neg.put(-7, 49);
        check(neg.get(-7) == 49, "negative key");

        // Many inserts keep the load factor under the limit
        ChainedHashTable<Integer, Integer> big = new ChainedHashTable<>(8, 0.75);
        for (int i = 0; i < 10_000; i++) {
            big.put(i, i * 2);
        }
        check(big.size() == 10_000 && big.get(9_999) == 19_998, "bulk");
        check((double) big.size() / big.capacity() <= 0.75, "load factor bound");
        System.out.println("PASS");
    }
}

Notice the removal trick in both versions. The code swaps the target entry with the last entry in its bucket and pops the end. Order inside a bucket does not matter, so this avoids shifting elements.

Dry run: inserting 5, 9, 2, 13 into four buckets

Integer keys make the trace easy to follow, because a small non-negative int hashes to itself in Python. The table starts with capacity 4 and a maximum load factor of 0.75.

Step Operation Index Buckets after the step Size Load factor
1 put 5 5 % 4 = 1 [ ], [5], [ ], [ ] 1 0.25
2 put 9 9 % 4 = 1 [ ], [5, 9], [ ], [ ] 2 0.50
3 put 2 2 % 4 = 2 [ ], [5, 9], [2], [ ] 3 0.75 (not above the limit)
4 put 13 13 % 4 = 1 [ ], [5, 9, 13], [2], [ ] 4 1.00, above 0.75, so resize
5 resize to 8 5→5, 9→1, 2→2, 13→5 [ ], [9], [2], [ ], [ ], [5, 13], [ ], [ ] 4 0.50
6 get 13 13 % 8 = 5 scan [5, 13], match on the second entry 4 0.50

Step 4 shows the failure mode in miniature: three keys in one bucket. Step 5 shows the cure. Doubling spreads the chain, because keys that agreed on their lowest two bits may disagree on the third.

Average case vs worst case: the real complexity

Here is the myth to drop: “hash map lookups are always O(1).” They are O(1) on average, under the assumption that the hash function spreads keys roughly uniformly. In the worst case every key lands in one bucket, and each lookup scans all n entries.

Operation Average case Worst case Why the worst case happens
get / contains O(1) O(n) All keys share one bucket
put O(1) amortized O(n) A single insert can trigger a full rehash
remove O(1) O(n) Same long bucket as lookup
resize O(n) O(n) Every entry gets a new index
iterate all entries O(n + capacity) O(n + capacity) Empty buckets are visited too
Space O(n) O(n) Capacity stays proportional to n

Two refinements matter. First, hashing is not free. A string key of length k costs O(k) to hash, so the constant is in the number of entries, not key size. Both CPython and Java cache a string’s hash after the first computation.

Second, Java narrowed the worst case. Since JDK 8, a HashMap bucket that reaches 8 entries becomes a balanced tree once the table has at least 64 buckets; smaller tables resize instead. Tree bins give O(log n) worst-case lookups when keys are Comparable or have distinct hashes. CPython’s dict has no tree fallback and relies on randomized string hashing instead.

Measure it yourself

A key class whose hash always returns 42 is legal, because equal keys still get equal hashes. It is also a disaster, since every key lands in one bucket. Build a dict of n such keys and the total work becomes quadratic. Run this and compare the two build times on your machine:

import timeit


class GoodKey:
    def __init__(self, v: int) -> None:
        self.v = v

    def __eq__(self, other: object) -> bool:
        return isinstance(other, GoodKey) and self.v == other.v

    def __hash__(self) -> int:
        return hash(self.v)


class ConstantHashKey(GoodKey):
    def __hash__(self) -> int:
        return 42  # legal, because equal keys still get equal hashes


def build_seconds(cls: type, n: int) -> float:
    return timeit.timeit(lambda: {cls(i): i for i in range(n)}, number=1)


if __name__ == "__main__":
    n = 2_000
    good = build_seconds(GoodKey, n)
    bad = build_seconds(ConstantHashKey, n)
    print(f"n={n}: good hash {good:.4f}s, constant hash {bad:.4f}s, ratio {bad / good:.0f}x")

    data = list(range(100_000))
    as_set = set(data)
    print("list membership:", timeit.timeit(lambda: 99_999 in data, number=200))
    print("set membership: ", timeit.timeit(lambda: 99_999 in as_set, number=200))
    assert len({ConstantHashKey(i): i for i in range(50)}) == 50  # still correct, just slow

Your exact numbers will differ by machine, so trust the ratio rather than the seconds. The constant-hash version should be slower by orders of magnitude, and the gap widens as you raise n. That ratio is the worst case from the table above, made visible.

Hashable keys: the equals and hashCode contract

A hash table makes one demand of its keys. If two keys are equal, they must produce the same hash code. The Java Object.hashCode contract states this rule, and the Python data model docs for __hash__ state the same rule for __hash__ and __eq__. The reverse is not required: unequal keys may share a hash, and that is just a collision.

A second rule is quieter: a key’s hash must not change while the key sits in the table. The entry was filed under its old hash, so after a change, lookups search the wrong bucket.

Python enforces part of this. Built-in mutable types such as list are unhashable and raise TypeError as keys. A class that defines __eq__ without __hash__ gets __hash__ set to None. Java enforces nothing: overriding equals without hashCode compiles and then fails lookups at run time.

In Python:

from dataclasses import FrozenInstanceError, dataclass


class MutablePoint:
    """Defines __eq__ and __hash__ from fields that can change: a trap."""

    def __init__(self, x: int, y: int) -> None:
        self.x = x
        self.y = y

    def __eq__(self, other: object) -> bool:
        return isinstance(other, MutablePoint) and (self.x, self.y) == (other.x, other.y)

    def __hash__(self) -> int:
        return hash((self.x, self.y))


@dataclass(frozen=True)
class Point:
    """eq=True plus frozen=True makes the dataclass generate a safe __hash__."""
    x: int
    y: int


class EqOnly:
    def __init__(self, v: int) -> None:
        self.v = v

    def __eq__(self, other: object) -> bool:
        return isinstance(other, EqOnly) and self.v == other.v


if __name__ == "__main__":
    # The mutable key bug: the entry is stranded in the bucket for its old hash
    p = MutablePoint(1, 2)
    seen = {p}
    p.x = 5
    assert p not in seen                 # looks in the bucket for hash((5, 2))
    assert MutablePoint(1, 2) not in seen  # right bucket, but the stored key now equals (5, 2)
    assert len(seen) == 1                # the entry still exists, just unreachable

    # The fix: an immutable key
    q = Point(1, 2)
    frozen_seen = {q}
    assert Point(1, 2) in frozen_seen    # equal objects, equal hashes
    try:
        q.x = 5                          # type: ignore[misc]
        raise AssertionError("frozen dataclass allowed mutation")
    except FrozenInstanceError:
        pass

    # Overriding __eq__ without __hash__ sets __hash__ to None
    assert EqOnly.__hash__ is None
    try:
        {EqOnly(1)}
        raise AssertionError("EqOnly should be unhashable")
    except TypeError:
        pass

    # Lists are unhashable; tuples of hashables are fine
    try:
        {[1, 2]: "x"}
        raise AssertionError("list key accepted")
    except TypeError:
        pass
    assert {(1, 2): "x"}[(1, 2)] == "x"
    print("all tests passed")

The same in Java:

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

public class HashKeyContract {

    // Broken: equals is overridden, hashCode is inherited from Object.
    static final class EqualsOnly {
        final int x;
        final int y;

        EqualsOnly(int x, int y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public boolean equals(Object o) {
            return o instanceof EqualsOnly other && x == other.x && y == other.y;
        }
    }

    // Correct: both methods use the same fields, and the fields are final.
    static final class GoodPoint {
        final int x;
        final int y;

        GoodPoint(int x, int y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public boolean equals(Object o) {
            return o instanceof GoodPoint other && x == other.x && y == other.y;
        }

        @Override
        public int hashCode() {
            return Objects.hash(x, y);
        }
    }

    // Also correct: a record generates equals and hashCode from its components.
    record Point(int x, int y) { }

    private static void check(boolean condition, String message) {
        if (!condition) {
            throw new AssertionError(message);
        }
    }

    public static void main(String[] args) {
        Set<GoodPoint> good = new HashSet<>();
        good.add(new GoodPoint(1, 2));
        check(good.contains(new GoodPoint(1, 2)), "GoodPoint lookup");
        check(!good.add(new GoodPoint(1, 2)), "GoodPoint duplicate rejected");

        Set<Point> records = new HashSet<>();
        records.add(new Point(1, 2));
        check(records.contains(new Point(1, 2)), "record lookup");

        // The broken class: equal objects almost always land in different buckets.
        Set<EqualsOnly> broken = new HashSet<>();
        broken.add(new EqualsOnly(1, 2));
        System.out.println("EqualsOnly found: " + broken.contains(new EqualsOnly(1, 2)));

        // The mutable key bug with a List key.
        List<Integer> key = new ArrayList<>(List.of(1, 2, 3));
        Set<List<Integer>> seen = new HashSet<>();
        seen.add(key);
        key.add(4); // hashCode changes from 30817 to 955331
        check(!seen.contains(key), "mutated key is lost");
        check(!seen.contains(List.of(1, 2, 3)), "old value is lost too");
        check(seen.size() == 1, "entry still occupies the table");

        // Empty and single-element edge cases
        Set<Point> empty = new HashSet<>();
        check(!empty.contains(new Point(0, 0)), "empty set");
        System.out.println("PASS");
    }
}

The wrong versions break one of two rules. Derive the hash from exactly the fields that equals compares, and make those fields immutable. Java records and Python frozen dataclasses do both, which makes them the safest keys.

Built-in hash tables in Python and Java

You will rarely write your own table outside an interview. You will use the built-ins every day, and each has behavior worth knowing.

Need Python 3.12 Java 21 Gotcha
Key to value dict HashMap map.get(k) returns null for a missing key and for a key mapped to null
Membership only set, frozenset HashSet HashSet is backed by a HashMap internally
Iteration order Insertion order, guaranteed since 3.7 No order guarantee; use LinkedHashMap for insertion order Never rely on HashMap order in tests
Shared across threads Guard compound updates with a lock Not synchronized; use ConcurrentHashMap Check-then-act races in both
Modify while iterating RuntimeError if the size changes ConcurrentModificationException Collect changes, apply after the loop

Two Python surprises are worth knowing. First, 1, 1.0, and True compare equal and hash equal, so they share one dict key. Second, string hashes are salted per process, and this randomization has been on by default since Python 3.3. Never persist hash() output to disk.

Where this shows up in real systems

  • Python’s own namespaces. Module globals, class attributes, and most instance attributes live in dicts, as the Python data model documents. Every attribute access on an ordinary object is, underneath, a hash table lookup. That is why CPython tunes its dict so heavily.
  • CPython’s compact dict. Since 3.6, CPython splits a dict into a small index array and a dense entries array, per the comments in dictobject.c. The index array does the hashing, and the entries array keeps insertion order and stays compact. That design is why insertion order became a language guarantee in 3.7.
  • Caches. An in-memory cache is a hash table from request key to stored result, often paired with a list that tracks recency. The classic LRU design combines a hash map with doubly linked lists for O(1) eviction. The Caching section covers how this scales beyond one process.

How to explain it in an interview

When an interviewer asks how hash tables work, walk the path of one lookup, then widen out. A strong answer follows this order.

  1. The path. Hash the key, compress to an index, scan the bucket, and confirm with equality.
  2. Collisions. They are unavoidable; name chaining and open addressing in one sentence each.
  3. Load factor and resizing. State the threshold, the doubling, and why inserts stay O(1) amortized.
  4. Complexity with qualifiers. Say “O(1) average, O(n) worst case,” and mention Java’s tree bins.
  5. The key contract. Equal keys need equal hashes, and keys must not change after insertion.

Expect these follow-ups.

  • “What happens if all keys collide?”
  • “Why is Java’s capacity a power of two?” Masking with (n - 1) & hash is cheaper than modulo, and HashMap mixes high bits into low bits to compensate.
  • “How would you make it thread-safe?”

A mistake I see often when candidates explain hash tables: they say “O(1)” and stop. When I ask what the worst case is and what causes it, many go quiet. The candidates who stand out name the uniform-hashing assumption without prompting. Then they describe one concrete way to break it, such as a constant hashCode or a mutated key. That single sentence signals you understand the structure rather than its marketing.

Decision framework: choosing a hash table

  1. Do you look things up by key, not by position? If you need the k-th element, use an array or list.
  2. Do you need sorted order or range queries? Use Java’s TreeMap or a sorted Python list with bisect.
  3. Is the key space small and dense? Lowercase letters or values from 0 to 1,000 fit a plain array of counts.
  4. Are your keys immutable with a correct hash? If not, fix the key type first.
  5. Could an attacker choose your keys? Rely on randomized string hashing or tree fallbacks, and cap input sizes.

When not to use a hash table

  • You need order. Questions such as “smallest key greater than x” or “all keys between a and b” need ordered structures. A binary search tree answers them in O(log n), while a hash table must scan everything.
  • The key range is tiny and known. Counting 26 lowercase letters with an array of 26 ints avoids hashing entirely. It also uses less memory and is easy to compare for equality.
  • Memory is tight and data is static. A sorted array with binary search stores no empty buckets and no per-entry overhead. It answers membership in O(log n), which is often fast enough.

Common mistakes

  • Mutating a key after insertion. The entry stays in the bucket for its old hash and becomes unreachable. Expose it by adding a list to a Java HashSet, appending to the list, and calling contains.
  • Overriding equals without hashCode. Equal objects get different identity hashes and land in different buckets. Two “equal” points both get added to a HashSet.
  • Quoting O(1) without a qualifier. Interviewers hear it as a gap in understanding. Say “average case” and know the worst case.
  • Modifying a map while iterating over it. Python raises RuntimeError: dictionary changed size during iteration, and Java throws ConcurrentModificationException. Deleting keys inside a for k in d loop exposes it.
  • Mixing numeric types as keys in Python. d[1] and d[1.0] are the same slot. Counting a list such as [1, 1.0, True] reports one key with count 3.

Practice problems

Problem Difficulty The twist
Contains Duplicate Easy A set replaces the nested loop; stop at the first repeat
Design HashSet Easy Build buckets yourself with no built-in hash containers
Design HashMap Easy Same as above, plus overwrite on duplicate keys and removal inside a chain
Two Sum Easy Store each value’s index and look up the complement before inserting
Insert Delete GetRandom O(1) Medium A map from value to array index plus swap-with-last deletion
LRU Cache Medium A hash map for lookup plus a doubly linked list for recency order
All O(1) Data Structure Hard Maps from key to count and from count to a bucket of keys, kept in sync

Key takeaways

  • How hash tables work fits in one line: hash the key, compress it to an index, and scan one bucket with equality checks.
  • Collisions are unavoidable. Chaining and open addressing are the two ways to absorb them.
  • Keep the load factor bounded by doubling, and inserts stay O(1) amortized despite O(n) resizes.
  • Always say “O(1) average, O(n) worst case,” and know that Java trees large buckets for O(log n).
  • Equal keys must have equal hashes, and a key’s hash must never change while it is stored.
  • Use records or frozen dataclasses for composite keys, and presize when you know the final count.
  • Pick a tree or sorted array when you need order, and a plain array when the key range is tiny.

Frequently Asked Questions

Why are hash table lookups O(1) on average but O(n) in the worst case?

A good hash function spreads keys evenly, so each bucket holds only a few entries and a lookup checks a constant number of them. If many keys land in the same bucket, a lookup must scan that whole bucket, which takes O(n) time. Java reduces this worst case to O(log n) by turning large buckets into balanced trees.

What happens when a hash table gets full?

It resizes before it gets full. When the load factor passes a threshold, 0.75 for Java HashMap and about two-thirds for a CPython dict, the table allocates a larger array and reinserts every entry. That single step costs O(n), but doubling keeps the average cost per insert constant.

Why must equal objects have equal hash codes?

The table uses the hash code to pick which bucket to search. If two equal objects had different hash codes, a lookup with one would search the wrong bucket and miss the other. Unequal objects may share a hash code, which is simply a collision.

Can a mutable object be a dictionary key in Python?

Built-in mutable types such as list, dict, and set cannot, and Python raises TypeError if you try. A custom class can be hashable while mutable, but changing the fields used by its hash strands the entry in the wrong bucket. Use tuples or frozen dataclasses for keys instead.

A hash table is only as fast as its worst bucket

Once you see how hash tables work, every guarantee reduces to keeping buckets short. The hash function spreads keys, the load factor caps crowding, and immutable keys keep entries where the table filed them. For more DSA patterns, see the DSA hub. Rule of thumb: say “average case” every time you say O(1), and never let a key change after you store it.

Originally posted on 30 November 2026 and post last modified on 2 December 2026

Coding Interviews Data Structures Hash Maps Hashing

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *