Hash Tables

Average O(1) insert, lookup and delete — hash functions, collisions, load factor, resizing and how HashMap really works.

Intermediate 4 min readLesson 6 of 16 Interview Q&A

A hash table maps keys to values with average O(1) insert, lookup and delete. It is arguably the most useful data structure in practice: Java's HashMap/HashSet, Python's dict/set, JavaScript's Map/Set, database hash indexes, caches and compilers' symbol tables.

The idea

Keep an array of buckets. To store a key, run it through a hash function that turns it into an integer, then map that integer to a bucket index:

index=hash(key) mod capacity\text{index} = \text{hash(key)} \bmod \text{capacity}

Lookup repeats the same computation and goes straight to the bucket — no searching.

"apple"keyhash()→ 93847102mod 8→ 6bucket[6]apple → 3
Key → hash code → bucket index → value

What makes a good hash function

  • Deterministic — equal keys always produce equal hashes.
  • Uniform — spreads keys evenly over buckets.
  • Fast — it runs on every operation.
  • For hash tables it does not need to be cryptographic (see Hash functions for that kind).

Collisions

Different keys can land in the same bucket — guaranteed once there are more keys than buckets (pigeonhole principle). There are two main strategies.

Separate chaining

Each bucket holds a small list of entries. Lookup hashes to the bucket, then scans its list.

0cat→11∅2dog→7owl→23ant→44∅5fox→9
'dog' and 'owl' collide in bucket 2 and are chained.

Java's HashMap uses chaining, and since Java 8 converts a bucket's list into a red-black tree once it exceeds 8 entries, so a pathological bucket costs O(log n) instead of O(n).

Open addressing

All entries live in the array itself. On collision, probe other slots:

  • Linear probing: try i, i+1, i+2, … — very cache-friendly, but suffers primary clustering.
  • Quadratic probing: i + 1², i + 2², ….
  • Double hashing: step size from a second hash function.

Deletion needs tombstones (a "deleted" marker) so later probes don't stop early. Python's dict and many high-performance tables (Google's SwissTable, Rust's HashMap) use open addressing.

Load factor and resizing

α=number of entriesnumber of buckets\alpha = \frac{\text{number of entries}}{\text{number of buckets}}

As α grows, chains (or probe sequences) get longer and operations slow down. When α crosses a threshold — 0.75 in Java, about 2/3 in Python — the table doubles its capacity and rehashes every entry. Like dynamic arrays, this is O(n) occasionally but amortized O(1) per insert.

OperationAverageWorst case
InsertO(1)O(n) (all keys collide)
LookupO(1)O(n) — O(log n) for treeified Java buckets
DeleteO(1)O(n)
Iterate in sorted order—Not supported; use a balanced BST / TreeMap

A minimal hash map

class MyHashMap<K, V> {
    private static class Entry<K, V> {
        final K key; V val; Entry<K, V> next;
        Entry(K k, V v, Entry<K, V> n) { key = k; val = v; next = n; }
    }
    @SuppressWarnings("unchecked")
    private Entry<K, V>[] buckets = new Entry[16];
    private int size;

    private int idx(Object key, int cap) {
        int h = key.hashCode();
        h ^= (h >>> 16);                // spread high bits (like java.util.HashMap)
        return h & (cap - 1);           // cap is a power of two → fast modulo
    }

    public V get(K key) {
        for (Entry<K, V> e = buckets[idx(key, buckets.length)]; e != null; e = e.next)
            if (e.key.equals(key)) return e.val;
        return null;
    }

    public void put(K key, V val) {
        int i = idx(key, buckets.length);
        for (Entry<K, V> e = buckets[i]; e != null; e = e.next)
            if (e.key.equals(key)) { e.val = val; return; }
        buckets[i] = new Entry<>(key, val, buckets[i]);
        if (++size > buckets.length * 3 / 4) resize();
    }

    @SuppressWarnings("unchecked")
    private void resize() {
        Entry<K, V>[] old = buckets;
        buckets = new Entry[old.length * 2];
        for (Entry<K, V> head : old)
            for (Entry<K, V> e = head; e != null; e = e.next) {
                int i = idx(e.key, buckets.length);
                buckets[i] = new Entry<>(e.key, e.val, buckets[i]);
            }
    }
}

Using hash maps in interviews

Hash maps turn O(n²) "search for a partner" loops into O(n) single passes.

Two Sum
int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> seen = new HashMap<>();   // value → index
    for (int i = 0; i < nums.length; i++) {
        Integer j = seen.get(target - nums[i]);
        if (j != null) return new int[]{j, i};
        seen.put(nums[i], i);
    }
    return new int[0];
}

Common uses: counting frequencies, deduplication (Set), grouping (anagrams), memoisation in dynamic programming, prefix-sum counts (Prefix sum), and graph adjacency lists.

Key takeaways
  • Hash → bucket index gives average O(1) operations.
  • Collisions are resolved by chaining or open addressing.
  • Keep the load factor bounded by resizing (amortized O(1)).
  • Worst case is O(n); languages randomise hash seeds to defend against hash-flooding attacks.
  • Equal objects must have equal hash codes.
Interview questions
QHow does Java's HashMap work internally?medium

An array of buckets (capacity a power of two, default 16). hash = h ^ (h >>> 16), index = hash & (n-1). Collisions chain in a linked list, converted to a red-black tree when a bucket exceeds 8 entries (and the table has at least 64 buckets). When size exceeds capacity × 0.75 the table doubles and entries are redistributed. It allows one null key and is not thread-safe — use ConcurrentHashMap.

QWhat is a hash-flooding attack?hard

An attacker submits many keys that collide (e.g., HTTP form parameter names), degrading every operation to O(n) and the server to O(n²) CPU. Defences: randomised per-process hash seeds (SipHash in Python, Rust, Ruby), treeified buckets (Java), and request limits.

QWhen would you choose a TreeMap over a HashMap?easy

When you need keys in sorted order, range queries (floorKey, subMap), or a guaranteed O(log n) worst case instead of average O(1).

QLongest consecutive sequence in an unsorted array in O(n).medium

Put all numbers in a set. For each x where x−1 is not in the set (the start of a run), count upward while x+1, x+2, … exist. Every number is visited at most twice.