Lesson 3 · Non-linear structures

Hash Tables, Hash Maps, and Hash Sets

A hash table computes an array index from each key with a hash function, so insert, lookup and delete take O(1) time on average. Collisions are handled by chaining or probing, and the table grows when it gets too full.

Hash Tables, Hash Maps, and Hash Sets concept diagramA visual explanation of the layout and operations shown in this lesson."Bob"hash("Bob") = 2bucket 0bucket 1"Bob"bucket 2bucket 3the hash function maps a key directly to a bucket index
1

From Key to Index in One Step

A hash table stores keys (or key-value pairs) so that any key can be found without searching. A hash function turns the key into an integer, and taking it modulo the array size gives a bucket index. Lookup computes that index and looks only there. This is what hashing means in data structures: computing where an item lives instead of searching for it.

That is why the operations are O(1) on average rather than O(log n): the position is computed, so the cost does not grow with the number of entries. A key-value table is usually called a hash map; one that stores keys only is a hash set.

A good hash function has three properties. It is deterministic: the same key always gives the same value, which is why keys must not change while stored. It spreads keys evenly, so no bucket becomes a hotspot. And it is fast, because it runs on every operation; cryptographic hashes are far too slow for this.

Java's String.hashCode illustrates the shape: h = 31·h + c for each character, a polynomial accumulation where the odd multiplier and overflow together scramble the bits. Note it is not random — it is a fixed function that happens to spread typical inputs well.

The equality contract is the part that causes real bugs. If two keys are equal they must hash identically, or a lookup will probe the wrong bucket and report a stored key as missing. In Java, overriding equals without overriding hashCode produces exactly this failure, and it is why the two must always be changed together. The converse is not required — unequal keys may share a hash, which is the collision case below.

  • Hash the key, reduce it modulo the table size, go to that bucket
  • Equal keys must hash equally, or lookups silently fail
  • Changing a key after inserting it strands the entry in the wrong bucket
2

Collision Resolution Techniques

Two distinct keys mapping to the same bucket is a collision, and it is not an edge case to be avoided — it is a mathematical certainty. There are infinitely many possible keys and finitely many buckets, so collisions must occur.

They occur far sooner than intuition suggests. By the birthday paradox, a table with 365 buckets holding just 23 random keys already has a 50% chance of a collision. Any hash table design must therefore handle them as a normal case.

Separate chaining makes each bucket a list of every entry that hashed there. Insert appends to the list; lookup hashes to the bucket and compares keys along that one list. It is simple, tolerates a load factor above 1, and deletion just removes a list node. The code below is a chaining table with 5 buckets.

Its weakness is pointer chasing through the lists. Java's HashMap limits the damage by turning a bucket's list into a balanced tree once it holds more than 8 entries (and the table has at least 64 buckets), so a crowded bucket costs O(log n) instead of O(n).

Open addressing keeps every entry in the array itself. On a collision it probes other slots by a fixed rule. Linear probing tries the next slot, then the next. It is fast on real hardware because it reads neighbouring memory, but it suffers primary clustering: occupied runs merge and grow, and every key that lands in a run must walk to its end. Quadratic probing steps by 1, 4, 9 and so on, which breaks up runs but may miss free slots unless the table size is chosen carefully. Double hashing takes the step size from a second hash, spreading keys best at the cost of a second hash.

Deletion is the awkward part of open addressing. Clearing a slot breaks the probe path: a later lookup stops at the gap and reports keys beyond it as missing. The fix is a tombstone, a marker meaning 'deleted, keep probing'. Inserts may reuse it, lookups step over it, and a rebuild clears them out.

Collision strategies compared
StrategyWhere entries liveStrengthWeakness
Separate chainingA list per bucketSimple; load factor may exceed 1Pointer chasing, extra memory
Linear probingThe next free slotBest cache localityPrimary clustering
Quadratic probingSlot + 1, 4, 9, …Breaks up clustersMay not probe every slot
Double hashingStep from a second hashBest distributionA second hash per probe
  • Chaining: a list per bucket; probing: another slot in the same array
  • Linear probing is cache-friendly but forms clusters
  • Open addressing deletes with tombstones, never by emptying a slot
3

Load Factor and Rehashing

The load factor is entries divided by buckets, and it is the single number governing a hash table's performance. A near-empty table wastes memory; a crowded one collides constantly.

With chaining, the average chain length is the load factor α, so at α = 0.75 most lookups compare one or two keys. Linear probing degrades much faster. Expected probes are about (1 + 1/(1 − α)) / 2 for a successful search and (1 + 1/(1 − α)²) / 2 for a miss: at α = 0.5 that is 1.5 and 2.5, at α = 0.9 it is 5.5 and 50.5. That is why open addressing tables rehash well before they are full, typically between 0.5 and 0.75, while chaining tolerates about 1.

When the load factor crosses a threshold, the table rehashes: allocate a larger array — usually double — and reinsert every entry. Reinsertion is required rather than copying, because the bucket index depends on the array size, so every key's position changes.

Rehashing is O(n), which is why insertion is amortised O(1) rather than guaranteed. Most inserts are constant time; occasionally one rebuilds the whole table. Where that pause matters, size the table up front when the count is roughly known, for example new HashMap<>(expectedSize) in Java or reserve(n) on a C++ std::unordered_map.

The doubling policy is what makes the amortisation work: each rehash costs more but happens exponentially less often, so total rehashing work across n insertions stays O(n).

Table size interacts with the hash. With a power-of-two size the modulo becomes a bitmask — very fast, but it uses only the low bits, so a hash with poor low-bit entropy clusters badly. Java addresses this by XOR-ing the high bits down before masking. A prime size mixes all bits naturally but requires a slower modulo operation.

  • Load factor = entries ÷ buckets
  • Chaining tolerates about 1; linear probing should stay under about 0.7
  • Rehashing reinserts every key, because each index depends on the table size
Key reference

Terms, operations, and practical uses

Core vocabulary

  • Hash FunctionAn algorithm that converts a key of any size into a fixed-size integer index.
  • BucketA specific slot in the hash table's underlying array where values are stored.
  • CollisionWhen two distinct keys are mapped to the exact same bucket index by the hash function.

Collision resolution

  • Separate ChainingHandling collisions by storing a linked list of entries at each bucket.
  • Open AddressingHandling collisions by probing other slots in the same array until a free one is found.
  • Linear ProbingThe simplest open addressing method: checking buckets one by one (i+1, i+2) until an empty spot is found.

Performance

  • Load FactorThe ratio of stored items to available buckets. High load factors increase collision rates.
  • RehashingCreating a larger underlying array and recalculating bucket indexes for all existing elements.
  • Amortized O(1)While rehashing is an O(N) operation, it happens so rarely that the average cost per insertion remains O(1).
Implementation

Code in Python, C++ and Java

def insert(hash_table, key):
    bucket = key % 5
    hash_table[bucket].append(key)

table = [[] for _ in range(5)]
insert(table, 15)
insert(table, 23)
insert(table, 10)
print('Bucket 0: ' + str(table[0]) + ', Bucket 3: ' + str(table[3]))
#include <iostream>
#include <vector>
using namespace std;

void insert(vector<vector<int>>& hashTable, int key) {
    int bucket = key % 5;
    hashTable[bucket].push_back(key);
}

int main() {
    vector<vector<int>> table(5);
    insert(table, 15);
    insert(table, 23);
    insert(table, 10);
    cout << "Bucket 0: [";
    for (size_t i = 0; i < table[0].size(); i++) { if (i) cout << ", "; cout << table[0][i]; }
    cout << "], Bucket 3: [";
    for (size_t i = 0; i < table[3].size(); i++) { if (i) cout << ", "; cout << table[3][i]; }
    cout << "]\n";
}
import java.util.*;

public class Main {
    static void insert(ArrayList<LinkedList<Integer>> hashTable, int key) {
        int bucket = key % 5;
        hashTable.get(bucket).add(key);
    }

    public static void main(String[] args) {
        ArrayList<LinkedList<Integer>> table = new ArrayList<>();
        for (int i = 0; i < 5; i++) table.add(new LinkedList<>());
        insert(table, 15);
        insert(table, 23);
        insert(table, 10);
        System.out.println("Bucket 0: " + table.get(0) + ", Bucket 3: " + table.get(3));
    }
}
Watch it run

Step through it

Running on insert 15, 23, 10 into 5 buckets with k % 5; then linear probing in 7 slots

separate chaining, 5 buckets, h(k) = k % 50151∅2∅3∅4∅bucketh(15) = 15 % 5 = 0 → bucket 0
Step 1

Insert 15: hash, then append

The code's table has 5 buckets, each holding a chain (a list). To insert a key, compute its bucket: 15 % 5 = 0, then append 15 to bucket 0's chain. No other key is looked at, which is why insertion is O(1) on average.

Output
1 / 12
4

Hash Table vs HashMap

Whether a hash table and a hash map differ depends on whether you mean the idea or a particular class.

As data structures they are the same. A hash map is a hash table that stores key-value pairs; a hash set is one that stores keys only. All use the same hash function, buckets and collision handling; only what a slot holds differs.

As Java classes they are different. Hashtable is the legacy class from Java 1.0: every method is synchronized, and it rejects null keys and values. HashMap (Java 1.2) is not synchronized and allows one null key and any number of null values, so it is faster in single-threaded code. For shared use across threads the answer is ConcurrentHashMap, which locks per bucket rather than the whole table.

Other languages use one name each: Python's dict, C++'s std::unordered_map, Go's map and JavaScript's Map are all hash tables. Practice problems like Two Sum, Group Anagrams and Contains Duplicate use one as a lookup table, and Design HashMap asks you to build the chaining version yourself.

Java: Hashtable vs HashMap vs ConcurrentHashMap
HashtableHashMapConcurrentHashMap
Thread-safeYes — every method synchronizedNoYes — per-bin locking
null keyNot allowedOne permittedNot allowed
null valuesNot allowedAny numberNot allowed
IntroducedJava 1.0Java 1.2Java 5
Use it whenLegacy code onlySingle-threaded — the defaultShared across threads
  • Data structures: hash table, hash map and hash set work the same way
  • Java: Hashtable is legacy and synchronized; HashMap is the default
  • For threads, use ConcurrentHashMap
5

Hash Table Time Complexity and What Breaks It

The honest statement of complexity is that insertion, lookup, and deletion are O(1) on average and O(n) in the worst case. The worst case occurs when every key hashes to the same bucket, collapsing the table into a single list.

This is not only theory. Hash functions are public and deterministic, so an attacker who controls the keys (form fields, JSON, HTTP headers) can send thousands that collide on purpose, turning each insert into O(n) and the whole request into O(n²). These hash-flooding attacks were shown against most major web frameworks in late 2011.

Two defences are used. Randomised hashing seeds the hash with a per-process secret so collisions cannot be predicted: Python (string hashing is randomised by default since 3.3, controlled by PYTHONHASHSEED), Ruby, Perl and Rust do this, which is also why a Python set of strings can print in a different order on each run. Java's String.hashCode is fixed, so Java relies instead on HashMap turning long buckets into trees.

Two more things you give up for O(1). A hash table has no useful order: iteration follows bucket layout, not sort order, so sorted output or range queries need a balanced tree at O(log n). Python's dict keeps insertion order because its implementation stores entries in a separate array, a language guarantee since Python 3.7, not a property of hashing.

And there is memory overhead: a table keeps empty buckets on purpose to stay under its load factor, so it uses noticeably more space than the entries alone. For string keys, see string hashing; for prefix queries a trie beats a hash table.

The common mistakes follow from all of the above: mutating a key after insertion, which strands the entry in the wrong bucket; overriding equals without hashCode; relying on iteration order; and assuming O(1) is a guarantee in latency-critical or adversarial contexts where it is only an average.

Hash table time complexity, by operation
OperationAverageWorst caseWhy the worst case happens
Lookup / searchO(1)O(n)Every key lands in one bucket, so the lookup degrades to scanning a list
InsertionO(1)O(n)Same collision collapse; a rehash also costs O(n), amortised to O(1) per insert
DeletionO(1)O(n)The entry must be found first, so it inherits lookup's worst case
IterationO(n + m)O(n + m)Every bucket is visited, including the empty ones — m is the table size
  • O(1) average, O(n) worst case when all keys share a bucket
  • Seeded hashes defend against crafted collisions
  • No order and spare space are the price of O(1)