Skip to content
Chethan Yadav_
Data Structures & Algorithms

DSA/Lesson 5 of 11/5 min read

Hashing

Hash tables, hash functions, collision resolution with chaining and open addressing, load factor, rehashing and hashing patterns.


On this page

Hash Table

A hash table maps keys to values with average O(1) insert, lookup and delete. It stores entries in an array of buckets and uses a hash function to pick the bucket.

bucket_index = hash(key) % capacity
OperationAverageWorst
InsertO(1)O(n)
SearchO(1)O(n)
DeleteO(1)O(n)

The worst case happens when many keys land in the same bucket. Language examples: Python dict, Java HashMap, C++ unordered_map, JavaScript Map.

Hash Function

Converts a key into an integer. A good hash function:

  • is deterministic (same key, same hash);
  • spreads keys uniformly across buckets;
  • is fast to compute;
  • uses the whole key (so similar keys do not cluster).

Common techniques

  • Division method: h(k) = k mod m, with m a prime not close to a power of 2.
  • Multiplication method: h(k) = floor(m * frac(k * A)), with A about 0.618.
  • Polynomial rolling hash for strings: h(s) = (s0 * p^(n-1) + s1 * p^(n-2) + ... ) mod M. Used in Rabin-Karp.

Contract in Java: if a.equals(b) then a.hashCode() == b.hashCode(). Overriding equals without hashCode breaks HashMap.

Pitfall: using mutable objects as keys. If the key changes after insertion, its hash changes and the entry is lost.

Collision

Two different keys hashing to the same bucket. By the pigeonhole principle collisions are unavoidable, and by the birthday paradox they show up sooner than expected (about sqrt(m) keys for m buckets). Two main strategies follow.

Separate Chaining

Each bucket holds a linked list (or a small tree) of entries.

bucket 0: (apple, 3) -> (grape, 1)
bucket 1: empty
bucket 2: (kiwi, 7)
  • Simple; deletion is easy.
  • Performance degrades gracefully as the table fills.
  • Extra memory for pointers, poorer cache locality.

Java 8 HashMap converts a chain to a red-black tree once it has more than 8 entries, making the worst case O(log n) per bucket.

Open Addressing

All entries live in the array itself. On collision, probe other slots until an empty one is found.

Linear Probing

Try h, h+1, h+2, .... Great cache performance, but suffers from primary clustering: long runs of filled slots grow longer.

Quadratic Probing

Try h + 1^2, h + 2^2, h + 3^2, .... Reduces primary clustering but causes secondary clustering (keys with the same start follow the same path).

Double Hashing

Step size comes from a second hash: h1(k) + i * h2(k). Best distribution of the three; h2 must never be 0.

Deletion with open addressing

You cannot just empty a slot, because it would break probe chains for later keys. Mark it with a tombstone instead. Tombstones are cleaned up on rehash.

ChainingOpen addressing
MemoryExtra pointersCompact array
CachePoorGood
Load factor above 1PossibleImpossible
DeletionEasyNeeds tombstones
Used byJava HashMapPython dict, Go maps (variant)

Load Factor

load factor = number of entries / number of buckets.

  • Higher load factor: less memory, more collisions.
  • Java HashMap resizes at 0.75. Open addressing tables usually keep it below 0.5 to 0.7.

Expected probes for a successful search with linear probing grow like 1 / (1 - alpha), so performance collapses as the table nears full.

Rehashing

When the load factor crosses the threshold, allocate a bigger array (usually 2x) and reinsert every entry with the new capacity. A single rehash is O(n), but it happens rarely, so insert stays O(1) amortized, the same argument as dynamic arrays.

Pitfall in latency-sensitive systems: a rehash causes a pause. Incremental rehashing (Redis) moves a few buckets per operation.

Hash Set

A hash table that stores only keys. Used for membership checks and deduplication in O(1) average.

Hashing patterns in interviews

ProblemIdea
Two SumMap value to index; look up target - x
Group anagramsKey = sorted string or count tuple
Longest consecutive sequenceSet; start counting only at numbers with no x - 1
Subarray sum equals kMap prefix sum to count
First non-repeating characterCount map, then second pass
Contains duplicate within kSliding window set
def two_sum(nums, target):
    seen = {}
    for i, x in enumerate(nums):
        if target - x in seen:
            return seen[target - x], i
        seen[x] = i

Hash table vs balanced BST

Hash tableBalanced BST (TreeMap)
LookupO(1) averageO(log n)
Ordered iterationNoYes
Range queries, floor, ceilingNoYes
Worst caseO(n)O(log n)
Hash flooding: an attacker who knows your hash function can send keys that all collide and turn O(1) into O(n), causing a denial of service. Languages defend with randomized seeds such as SipHash.

Quick revision

  • Hash table: average O(1), worst O(n) when everything collides.
  • Good hash: deterministic, uniform, fast; never use mutable keys.
  • Chaining stores lists per bucket; open addressing probes within the array.
  • Linear probing clusters, quadratic reduces it, double hashing is best.
  • Open addressing deletes with tombstones.
  • Resize at a load factor threshold (0.75 in Java); rehash is O(n) but O(1) amortized.
  • Use a BST instead when you need ordering or range queries.