Introduction

A dictionary stores a set of keys (each possibly with satellite data) and supports INSERT, SEARCH and DELETE. A sorted array answers SEARCH in Θ(lg⁡n)\Theta(\lg n) time and a balanced search tree does all three in O(lg⁡n)O(\lg n). Hashing does all three in O(1)O(1) expected time under reasonable assumptions, by computing where a key lives instead of searching for it.

The price is order. A hash table scatters keys on purpose, so it cannot report the minimum, the successor of a key or all keys in a range without examining the whole table.

This note covers direct addressing, the hash table, the load factor, the standard hash functions (division, multiplication, mid-square, folding, strings and universal hashing) and the probability that keys collide. What a table does after a collision (chaining, linear, quadratic and double probing, and their expected costs) is the subject of Collision Resolution.

Prerequisites

Core concepts

Universe, keys and slots

  • The universe UU is the set of all possible keys, for example all 32-bit integers or all strings of length at most 20.
  • The key set K⊆UK \subseteq U is the set actually stored, with n=∣K∣n = |K|. Usually n≪∣U∣n \ll |U|.
  • A hash table T[0..m−1]T[0..m-1] has mm slots. A hash function h:U→{0,1,…,m−1}h : U \to \{0, 1, \ldots, m-1\} sends key kk to slot h(k)h(k), the home slot or hash value of kk.
  • A collision is a pair of distinct keys k1≠k2k_1 \ne k_2 with h(k1)=h(k2)h(k_1) = h(k_2).

Collisions are unavoidable. If ∣U∣>m|U| > m, the pigeonhole principle forces at least two keys of UU into one slot, so no hash function avoids collisions for every possible key set. A good hash function only makes them rare and evenly spread; a collision-resolution method handles the ones that happen.

Slot numbering convention. Hash table slots are numbered 00 to m−1m - 1, because every standard hash function produces a remainder. Other arrays in these notes are 1-based.

Direct addressing

When U={0,1,…,∣U∣−1}U = \{0, 1, \ldots, |U| - 1\} is small, use a direct-address table T[0..∣U∣−1]T[0..|U|-1] with one slot per possible key: slot kk holds the element with key kk, or NIL.

Pseudocode uses <- for assignment, x.key for the key of element x, NIL for an empty slot, and 0-based slots T[0..m−1]T[0..m-1].

Text
DIRECT-ADDRESS-SEARCH(T, k)
1  return T[k]

DIRECT-ADDRESS-INSERT(T, x)
1  T[x.key] <- x

DIRECT-ADDRESS-DELETE(T, x)
1  T[x.key] <- NIL

Each operation is Θ(1)\Theta(1) in the worst case, and space is Θ(∣U∣)\Theta(|U|). This is the right choice when ∣U∣|U| is comparable to nn (for example, keys are roll numbers 0 to 999). When ∣U∣|U| is huge and nn is small, the space is wasted, and hashing replaces T[k]T[k] by T[h(k)]T[h(k)] with m=Θ(n)m = \Theta(n) slots.

Load factor and simple uniform hashing

The load factor of a table holding nn keys in mm slots is

α=nm.\alpha = \frac{n}{m}.

With chaining α\alpha can exceed 1; with open addressing α≤1\alpha \le 1 always.

Simple uniform hashing is the assumption that each key is equally likely to hash to any of the mm slots, independently of where other keys hash. It is an idealisation (a fixed hh is deterministic), but it is the model in which expected costs such as Θ(1+α)\Theta(1 + \alpha) for search with chaining are proved. Under it, two fixed distinct keys collide with probability exactly 1/m1/m.

Expected versus worst case. Chaining under simple uniform hashing gives O(1)O(1) expected time per operation when α=O(1)\alpha=O(1). For open addressing, require α≤1−ε\alpha\le1-\varepsilon for fixed ε>0\varepsilon>0 and the appropriate uniform-hashing assumptions. The worst case is still Θ(n)\Theta(n) per search: if all nn keys land in one slot, the table degenerates into a list.

What makes a hash function good

  1. Deterministic: the same key always gets the same slot.
  2. Fast: O(1)O(1) for a fixed-size key, O(L)O(L) for a string of length LL.
  3. Uses all of the key: every bit or digit of the key should affect h(k)h(k), so that keys differing only in some positions still spread.
  4. Spreads the actual key set evenly over all mm slots, including keys with patterns (all even, all multiples of 10, common prefixes).

Hash functions

Division method

h(k)=k mod m.h(k) = k \bmod m.

One division, so it is fast. Its quality depends entirely on mm.

  • Avoid m=2pm = 2^p. Then k mod 2pk \bmod 2^p is the lowest pp bits of kk, and the other bits are ignored. With m=16m = 16, the keys 16,32,48,64,8016, 32, 48, 64, 80 all hash to slot 0.
  • Avoid m=10pm = 10^p for decimal keys, for the same reason: only the last pp digits count.
  • Choose mm prime, not close to a power of 2. With m=17m = 17 the same five keys go to slots 16,15,14,13,1216, 15, 14, 13, 12.

EDGE CASE. For negative keys, the mathematical k mod mk \bmod m lies in 0..m−10..m-1 (for example −3 mod 11=8-3 \bmod 11 = 8), but C's % operator gives −3-3 for -3 % 11. A question that uses C code means C's operator.

Multiplication method

Choose a constant AA with 0<A<10 < A < 1 and set

h(k)=⌊m (kA mod 1)⌋,h(k) = \left\lfloor m \,(kA \bmod 1) \right\rfloor,

where kA mod 1=kA−⌊kA⌋kA \bmod 1 = kA - \lfloor kA \rfloor is the fractional part of kAkA. The value of mm is not critical, so a power of 2 is fine and convenient. The golden-ratio choice A=(5−1)/2≈0.6180339887A = (\sqrt{5} - 1)/2 \approx 0.6180339887 is the usual recommendation and works well in practice.

Fixed-point form (word size ww, m=2pm = 2^p). Assume integer 1≤p≤w1\le p\le w and a nonnegative ww-bit key. Let s=⌊A⋅2w⌋s=\lfloor A\cdot2^w\rfloor and A′=s/2wA\prime=s/2^w. This word method implements multiplication hashing for the fixed-point constant A′A\prime, approximating the chosen real AA. Multiply the ww-bit key by ss to get a 2w2w-bit product r12w+r0r_1 2^w + r_0. Then h(k)h(k) is the most significant pp bits of the low word r0r_0, that is h(k)=⌊r0/2w−p⌋h(k) = \lfloor r_0 / 2^{w-p} \rfloor.

Text
HASH-MULTIPLY(k, s, w, p)
1  r <- k * s                       // 2w-bit product
2  r0 <- r mod 2^w                  // low word
3  return floor(r0 / 2^(w - p))      // top p bits of the low word

Evaluation costs. On a word model with constant-time sufficiently wide multiplication, masking and shifting, HASH-MULTIPLY takes Θ(1)\Theta(1) time and O(1)O(1) auxiliary words in best, average and worst cases. A constant number of words must hold the exact 2w2w-bit product (or a primitive must return its low word exactly); signed overflow is not a substitute. The input key and one-word hash output are excluded. These are word-operation costs, not bit-complexity bounds as ww grows.

Fixed-point multiplication method
Figure 1. The multiplication method with w=32w = 32, p=14p = 14, k=123456k = 123456 and s=2654435769s = 2654435769: the 64-bit product splits into r1=76300r_1 = 76300 and r0=17612864r_0 = 17612864, and the top 14 bits of r0r_0 give h(k)=67h(k) = 67.

Mid-square and folding

  • Mid-square: square the key and take the middle rr digits (or bits). For k=3121k = 3121, k2=9740641k^2 = 9740641, and the middle three digits give h(k)=406h(k) = 406 for a table of 1000 slots. The middle digits depend on every digit of kk.
  • Folding (shift folding): cut the key into equal parts and add them, then reduce modulo mm. For k=123456789k = 123456789 and 3-digit parts, 123+456+789=1368123 + 456 + 789 = 1368, and 1368 mod 1000=3681368 \bmod 1000 = 368.

Hashing strings

Evaluate the string polynomial ∑icode⁡(ci)RL−1−i\sum_i \operatorname{code}(c_i)R^{L-1-i} modulo mm using Horner's rule. The stored hh is in 0,…,m−10,\ldots,m-1; before reduction, hR+code⁡(c)≤(m−1)R+Cmax⁡hR+\operatorname{code}(c)\le(m-1)R+C_{\max}, where Cmax⁡C_{\max} is the largest character code. The simpler bound <Rm<Rm requires every code to be less than RR. Choosing R=31R=31 with ASCII is a polynomial hash, not an assertion that ASCII codes are base-31 digits:

Text
HASH-STRING(c, L, R, m)
1  h <- 0
2  for i <- 0 to L - 1
3      h <- (h * R + code(c[i])) mod m
4  return h

The result equals (∑i=0L−1code(ci) RL−1−i) mod m\left(\sum_{i=0}^{L-1} \mathrm{code}(c_i)\, R^{L-1-i}\right) \bmod m, because reduction modulo mm commutes with addition and multiplication. Summing the character codes without the powers of RR is a poor hash: every anagram ("TEA", "EAT", "ATE") collides.

Evaluation costs. HASH-STRING takes Θ(L+1)\Theta(L+1) time in best, average and worst cases, including the empty string, and O(1)O(1) auxiliary words excluding the input string and scalar hash output. Each character lookup, multiply-add and modulo must be constant time and exact at the chosen widths: an intermediate register must hold (m−1)R+Cmax⁡(m-1)R+C_{\max}, or use an equivalent overflow-safe modular primitive. Arbitrary-precision arithmetic has additional bit costs; silent machine overflow need not preserve the hash.

Universal hashing

An adversary knowing a fixed hh may choose colliding keys when a bucket contains enough of them. By the pigeonhole principle, some bucket has at least ⌈∣U∣/m⌉\lceil |U|/m\rceil keys; an all-colliding nn-set is guaranteed only for n≤⌈∣U∣/m⌉n\le\lceil |U|/m\rceil. The universal-hashing guarantee below is for a fixed key set chosen independently of the random hash. Universal hashing picks hh at random, at run time, from a family H\mathcal{H}. The family is universal if for every pair of distinct keys k≠lk \ne l,

Pr⁡h∈H[h(k)=h(l)]≤1m.\Pr_{h \in \mathcal{H}}[h(k) = h(l)] \le \frac{1}{m}.

A standard universal family. Restrict this family to integer keys in U⊆{0,…,p−1}U\subseteq\{0,\ldots,p-1\}, with prime pp and integer m≥1m\ge1. Choose aa and bb uniformly and independently from their respective sets, and for a∈{1,…,p−1}a \in \{1, \ldots, p-1\}, b∈{0,…,p−1}b \in \{0, \ldots, p-1\} set

ha,b(k)=((ak+b) mod p) mod m.h_{a,b}(k) = ((ak + b) \bmod p) \bmod m.

There are p(p−1)p(p-1) equally likely parameter pairs (a,b)(a,b); for some allowed UU and mm, different pairs represent the same map. For example, with p=17p = 17, m=6m = 6, h3,4(8)=((24+4) mod 17) mod 6=11 mod 6=5h_{3,4}(8) = ((24 + 4) \bmod 17) \bmod 6 = 11 \bmod 6 = 5. With chaining and a universal family, the expected chain length seen by a search is at most 1+α1 + \alpha for every key set, because the randomness is in the choice of hh, not in the input.

Worked examples

Division method with collisions

Insert 54,26,93,17,77,31,44,2054, 26, 93, 17, 77, 31, 44, 20 into a table with m=11m = 11 and h(k)=k mod 11h(k) = k \bmod 11.

Key5426931777314420
h(k)h(k)104560909

Two collisions occur: 4444 with 7777 at slot 0, and 2020 with 3131 at slot 9. The load factor is α=8/11≈0.727\alpha = 8/11 \approx 0.727. Under simple uniform hashing the expected number of colliding pairs among 8 keys is (82)/11=28/11≈2.55\binom{8}{2}/11 = 28/11 \approx 2.55, so two pairs is typical.

Keys mapped into an 11-slot table by k mod 11
Figure 2. Eight keys hashed by h(k)=k mod 11h(k) = k \bmod 11 into slots 0 to 10: 77 and 44 both go to slot 0 and 31 and 20 both go to slot 9; the other keys land in distinct slots.

Multiplication method

For k=123456k = 123456, A=(5−1)/2A = (\sqrt{5} - 1)/2 and m=10000m = 10000: kA≈76300.0041151kA \approx 76300.0041151, so kA mod 1≈0.0041151kA \bmod 1 \approx 0.0041151 and h(k)=⌊10000×0.0041151⌋=41h(k) = \lfloor 10000 \times 0.0041151 \rfloor = 41.

In fixed point with w=32w = 32, p=14p = 14 (m=16384m = 16384) and s=2654435769s = 2654435769 (so s/232≈0.6180339886s / 2^{32} \approx 0.6180339886): ks=327706022297664=76300⋅232+17612864ks = 327706022297664 = 76300 \cdot 2^{32} + 17612864, so r1=76300r_1 = 76300, r0=17612864r_0 = 17612864, and h(k)=⌊17612864/218⌋=67h(k) = \lfloor 17612864 / 2^{18} \rfloor = 67 (Figure 1).

A string with Horner's rule

Hash "GATE" with ASCII codes (G = 71, A = 65, T = 84, E = 69), R=31R = 31 and m=13m = 13:

StepCharacterhh after the step
1G(0⋅31+71) mod 13=6(0 \cdot 31 + 71) \bmod 13 = 6
2A(6⋅31+65) mod 13=251 mod 13=4(6 \cdot 31 + 65) \bmod 13 = 251 \bmod 13 = 4
3T(4⋅31+84) mod 13=208 mod 13=0(4 \cdot 31 + 84) \bmod 13 = 208 \bmod 13 = 0
4E(0⋅31+69) mod 13=4(0 \cdot 31 + 69) \bmod 13 = 4

Check without intermediate reduction: 71⋅313+65⋅312+84⋅31+69=218029971 \cdot 31^3 + 65 \cdot 31^2 + 84 \cdot 31 + 69 = 2180299, and 2180299 mod 13=42180299 \bmod 13 = 4.

How likely is a collision?

For integers m≥1m\ge1 and 0≤n≤m0\le n\le m, the formula below applies; for n>mn>m, P(no collision)=0P(\text{no collision})=0.

Under simple uniform hashing, the probability that nn keys in mm slots are all in different slots is

P(no collision)=∏i=0n−1m−im=m!(m−n)! mn,P(\text{no collision}) = \prod_{i=0}^{n-1} \frac{m - i}{m} = \frac{m!}{(m-n)!\, m^n},

and the expected number of colliding pairs is (n2)/m=n(n−1)/(2m)\binom{n}{2} / m = n(n-1)/(2m) (exact, by linearity of expectation over the (n2)\binom{n}{2} pairs). With m=365m = 365 and n=23n = 23, P(no collision)≈0.4927P(\text{no collision}) \approx 0.4927, so a collision is more likely than not: this is the birthday paradox. Collisions appear once nn is around m\sqrt{m}, long before the table is full.

Two more quantities follow from the same independence.

  • A given set of slots stays empty. A fixed slot misses one key with probability 1−1/m1 - 1/m, so after nn insertions a fixed set of ss slots is still empty with probability (1−s/m)n(1 - s/m)^n. With m=100m = 100 and n=3n = 3, the probability that slots 0, 1 and 2 are all still empty is (97/100)3=0.912673(97/100)^3 = 0.912673. This form is a common GATE question.
  • Expected number of empty slots is m(1−1/m)nm (1 - 1/m)^n, by linearity over the mm slots. With m=11m = 11 and n=8n = 8 it is 11(10/11)8≈5.1311 (10/11)^8 \approx 5.13; the division example above, with 8 keys in 6 distinct slots, leaves 5 empty, close to that value. When n=mn = m the fraction of empty slots tends to 1/e≈0.3681/e \approx 0.368.

Mathematical explanation

Why a power of 2 is bad for the division method

Write k=q⋅2p+rk = q \cdot 2^p + r with 0≤r<2p0 \le r < 2^p. Then k mod 2p=rk \bmod 2^p = r, the last pp bits. Keys that agree in their low bits collide regardless of their high bits; for example, all multiples of 2p2^p go to slot 0. A prime mm far from a power of 2 makes k mod mk \bmod m depend on all bits of kk.

Common factors. If keys share a factor dd with mm (all keys even and mm even), then k mod mk \bmod m is also a multiple of gcd⁡(d,m)\gcd(d, m), so only m/gcd⁡(d,m)m/\gcd(d, m) slots are ever used. With mm prime, gcd⁡(d,m)=1\gcd(d, m) = 1 for every d<md < m.

Expected cost depends on α\alpha, not on nn

Under simple uniform hashing with chaining, an unsuccessful search examines on average α\alpha keys (the expected length of one chain) plus the cost of computing hh, so it takes Θ(1+α)\Theta(1 + \alpha) time. If mm grows with nn so that α=O(1)\alpha = O(1) (for example, double mm and rehash when α\alpha passes a threshold), every operation is O(1)O(1) expected. Doubling makes the rehashing cost O(1)O(1) amortised per insertion, because the sizes m,2m,4m,…m, 2m, 4m, \ldots form a geometric series. The full analysis, including open addressing, is in Collision Resolution.

Important properties and observations

OperationDirect addressingChaining, expected (simple uniform hashing, α=O(1)\alpha=O(1))Hashing, worst caseBalanced BST
SEARCHΘ(1)\Theta(1)O(1)O(1)Θ(n)\Theta(n)O(lg⁡n)O(\lg n)
INSERTΘ(1)\Theta(1)O(1)O(1)Θ(n)\Theta(n) with a duplicate check, else O(1)O(1) with chainingO(lg⁡n)O(\lg n)
DELETEΘ(1)\Theta(1)O(1)O(1)Θ(n)\Theta(n)O(lg⁡n)O(\lg n)
MIN, successor, rangeΘ(∣U∣)\Theta(\lvert U \rvert)Θ(m+n)\Theta(m + n)Θ(m+n)\Theta(m + n)O(lg⁡n)O(\lg n) plus output
SpaceΘ(∣U∣)\Theta(\lvert U \rvert)Θ(m+n)\Theta(m + n)Θ(m+n)\Theta(m + n)Θ(n)\Theta(n)

Common misconceptions.

  • "A good hash function prevents collisions." No function can, once ∣U∣>m|U| > m; it can only spread them.
  • "Hashing is O(1)O(1)." Only in expectation, and for chaining with α=O(1)\alpha=O(1) under simple uniform hashing; open addressing instead needs α≤1−ε\alpha\le1-\varepsilon for fixed ε>0\varepsilon>0 and suitable uniform-hashing assumptions. The worst case is Θ(n)\Theta(n).
  • "The multiplication method needs a prime mm." It does not; m=2pm = 2^p is the usual choice. The prime-mm advice is for the division method.
  • "Universal hashing assumes random keys." It assumes nothing about the keys; the random choice of hh supplies the randomness.

Hashing versus search trees. Use a hash table for pure lookup by key. Use a search tree when the question needs order: sorted output, the minimum, the predecessor or successor, or a range query. A binary search tree answers those in time proportional to its height.

GATE examination perspective

  • DIVISION ARITHMETIC. Compute k mod mk \bmod m carefully for every key, in the given order, then count collisions or occupied slots. Write the slot list before drawing anything.
  • POWER-OF-TWO TABLE SIZE. Recognise that m=2pm = 2^p or m=10pm = 10^p with the division method keeps only the low bits or digits, so patterned keys cluster.
  • MULTIPLICATION METHOD. Fractional part first, then multiply by mm, then floor. In the fixed-point form, take the top pp bits of the low word, not of the whole product.
  • LOAD FACTOR. α=n/m\alpha = n/m, keys over slots. With open addressing α≤1\alpha \le 1.
  • PROBABILITY TRAPS. Two distinct keys collide with probability 1/m1/m under simple uniform hashing; the expected number of colliding pairs among nn keys is n(n−1)/(2m)n(n-1)/(2m); the probability of no collision is the falling product ∏(m−i)/m\prod (m-i)/m, not (1−1/m)n(1 - 1/m)^n.
  • STRING HASHES. Reduce modulo mm at every Horner step; sums of character codes make all anagrams collide.
  • EMPTY SLOTS. A fixed set of ss slots survives nn insertions empty with probability (1−s/m)n(1 - s/m)^n; the expected number of empty slots is m(1−1/m)nm(1 - 1/m)^n.

Summary

Sources

  1. T. H. Cormen, C. E. Leiserson, R. L. Rivest, C. Stein, Introduction to Algorithms, 3rd ed., MIT Press, 2009: Chapter 11, Sections 11.1 (direct-address tables), 11.2 (hash tables) and 11.3 (hash functions: division, multiplication and universal hashing).

Next steps