Simple Algorithm
Algorithms & Data Structures · Brute Force · 17 min

Hashing & String Algorithms

Constant-time lookup, and fingerprints that find patterns in text.

Is this username already taken? Checking a list of a billion names one by one takes a billion comparisons. A hash table answers in a step or two, because it computes where the name would be instead of searching for it. The same trick, turning data into a short number, finds phrases in text, and a tree of shared prefixes finishes your words as you type.

What you’ll learn

  • Explain how a hash function turns a key into a slot, and why collisions cannot be avoided.
  • Compare chaining and open addressing, and explain why tables resize as their load factor grows.
  • Say what "O(1)O(1) on average" promises for Python's dict, C++'s unordered_map and Java's HashMap, and what an adversary can do to it.
  • Use hashes as fingerprints to find a pattern in a text, and say what KMP and tries add.
  • Recognize when a problem calls for a hash map, a string-matching algorithm or a trie.

Have I seen this before?

Many programs ask one question over and over: is this key in my collection? Has this web page been crawled already? Is this word in the dictionary? Did this number appear earlier in the input?

The obvious answer keeps the keys in a list and scans it. One question costs up to nn comparisons, so asking it for each of nn items costs about n2/2n^2/2: for a million items, half a trillion comparisons. Sorting the keys and using binary search brings one question down to about log⁡2n\log_2 n comparisons, 20 for a million. A hash table usually needs just one or two steps.

The trick is to compute an address from the key. A hash function hh maps every key to one of mm slots of an array. To insert a key, compute h(key)h(\text{key}) and store the key in that slot. To look it up later, compute h(key)h(\text{key}) again and look in that one slot. Nothing is searched.

For whole numbers the simplest hash function is the remainder, h(k)=k mod mh(k) = k \bmod m. With m=11m = 11 slots, the key 57 goes to slot 57 mod 11=257 \bmod 11 = 2, and 25 goes to slot 3.

Collisions are unavoidable

Could a cleverer hash function avoid collisions altogether? Not when the keys are not known in advance. There are vastly more possible keys than slots (every possible username, every 64-bit number), so by the pigeonhole principle some slot is the home of a great many possible keys. And collisions arrive much sooner than intuition suggests.

Predict before you look

Birthdays behave like a hash function from people to 365 slots. How many randomly chosen people must be in a room before the chance that two of them share a birthday passes 50%?

Show the answer

23 people

Only 23 (the chance is 50.7%). Twenty-three people form (232)=253\binom{23}{2} = 253 pairs, and every pair is a chance to match. In general, with mm slots a collision becomes more likely than not after about 1.18m1.18\sqrt m random keys: a table with a million slots probably has a collision after 1,178 keys, when it is 0.1% full. This is the birthday paradox.

So every hash table needs a plan for collisions. There are two classic plans:

StrategyWhere colliding keys goHow a lookup works
ChainingEach slot holds a list (a chain) of every key that hashed thereCompute the slot, then scan its chain
Open addressingOne key per slot. A key whose slot is taken tries other slots in a fixed order, its probe sequence, until it finds a free oneFollow the same probe sequence until you meet the key or an empty slot
The simplest probe sequence is linear probing: try slot hh, then h+1h + 1, h+2h + 2, and so on, wrapping around at the end of the array.

Load factor and resizing

How full a table is matters more than how big it is. The load factor α=n/m\alpha = n/m counts keys per slot: with chaining, the average chain holds α\alpha keys. With linear probing, clusters grow much faster than α\alpha as the table fills. If the hash function scatters keys like random numbers, the expected costs are:

Load factor α\alphaChaining: keys compared to find a stored keyLinear probing: probes to find a stored keyLinear probing: probes to learn a key is absent
50%1.251.52.5
75%1.3752.58.5
90%1.455.550.5
Chaining compares 1+α/21 + \alpha/2 keys on average. The linear-probing columns are Knuth's classic estimates 12(1+11−α)\tfrac12\big(1 + \tfrac{1}{1-\alpha}\big) and 12(1+1(1−α)2)\tfrac12\big(1 + \tfrac{1}{(1-\alpha)^2}\big), derived in the Optimized lesson Hash Tables. Going from 75% to 90% full makes absent-key lookups six times slower.

So real tables never let α\alpha grow far. When an insertion would push the load factor past a threshold (0.75 is common), the table allocates about twice as many slots and rehashes: it reinserts every key, since with a new mm every key's slot changes. That one insertion costs O(n)O(n), but it happens so rarely that the average cost per insertion stays O(1)O(1), by the same doubling argument that makes appending to a dynamic array cheap. An average over a whole sequence of operations like this is an amortized cost.

When hashing goes wrong

The worst case is not just theory. If the hash function is fixed and public, an attacker can compute keys that all land in one slot. Then every insertion scans all the keys inserted before it, and nn insertions cost 0+1+⋯+(n−1)≈n2/20 + 1 + \dots + (n-1) \approx n^2/2 comparisons.

In December 2011, researchers showed that the web platforms of PHP, Java, Python, Ruby and others stored the fields of every submitted web form in exactly such tables. A single request full of colliding field names could keep a server's processor fully busy for a long time. This attack is called hash flooding.

The defenses are the subject of the Optimized lessons on hash tables and universal hashing: draw the hash function at random (universal hashing), or use a keyed hash function such as SipHash with a secret key, as Python and Rust do for their built-in tables. If you run the same Python program twice, hash("hello") gives different numbers, because every Python process picks its own random key for hashing strings.

Check your understanding

You insert nn keys into a hash table that doubles its number of slots whenever the load factor passes 0.75. The hash function spreads keys well. Which statement is true?

  1. Every insertion takes O(1)O(1) time
  2. The nn insertions take O(n)O(n) time in total on average, although a few of them take Θ(n)\Theta(n) each
  3. Insertions keep getting slower as the table grows, because every rehash copies more keys
  4. The table would be faster if it never resized and simply let its chains grow
Show the answer

B. The nn insertions take O(n)O(n) time in total on average, although a few of them take Θ(n)\Theta(n) each

A resize copies every key, so that one insertion costs Θ(n)\Theta(n). But resizes happen at sizes that double, so the copying adds up to less than 2n2n in total: O(1)O(1) amortized per insertion, on top of the expected O(1)O(1) for the insertion itself.

Fingerprints for strings

Hashing works on text too. Comparing two strings of length LL character by character costs up to LL steps. If you have a short hash of each, different hashes prove at once that the strings differ. Equal hashes do not prove that they are equal (collisions again), so a match is confirmed by actually comparing the characters. Hashes used this way are fingerprints.

Now look for a pattern pp of length mm in a text tt of length nn, the problem of pattern matching. The naive method tries every alignment and compares character by character: up to (n−m+1) m(n - m + 1)\,m comparisons. Rabin–Karp compares the fingerprint of each length-mm window of the text with the pattern's fingerprint instead, and compares characters only when the fingerprints agree.

Computing each window's fingerprint from scratch would cost mm steps, no better than comparing. The trick is a rolling hash. Treat a window of digits as a number: from 3141, slide one step to 1415 by removing the leading 3, shifting, and appending the 5:

1415=(3141−3⋅1000)⋅10+51415 = (3141 - 3 \cdot 1000) \cdot 10 + 5
Rabin–Karp does the same with characters as digits in base 256, keeping only the remainder modulo a prime qq so the numbers stay small. Sliding the window costs O(1)O(1), however long the pattern.
Think first Why not let Rabin–Karp report an occurrence as soon as a window's hash equals the pattern's, and skip the character check?

Because different strings can share a hash. With q=13q = 13 there are only 13 possible fingerprints, so a random window matches the pattern's by accident about once in 13 windows. The check costs up to mm comparisons, and with a large, randomly chosen prime qq it is almost never wasted: the expected running time is O(n+m)O(n + m) plus mm for each real occurrence.

Can you avoid hashing and still never waste comparisons? When naive matching fails after matching 6 characters, it shifts the pattern by one place and re-reads text it has already seen. KMP (Knuth, Morris & Pratt, 1977) first studies the pattern itself and records, for each prefix, how far the pattern can safely slide after a mismatch. Its search never moves backward in the text and makes at most 2n2n comparisons, whatever the input.

Tries: searching by prefix

A hash table answers "is cat stored?" in a step or two, but it is helpless with "which stored words start with ca?". The hashes of cat and car are unrelated, so it would have to check every word.

A trie (from retrieval, usually pronounced "try") stores words letter by letter in a tree. The root's children are the possible first letters, their children the second letters, and so on. Words with a common prefix share the path that spells it, and a mark on a node says that a word ends there. Looking up a word of length LL walks down LL edges, so its cost depends on the length of the word, not on how many words are stored. To autocomplete, walk down the prefix, then list every word below that node.

Tries power autocomplete, spell checkers, and the longest-prefix matching that routers use to forward IP addresses. They also lead to the most powerful string indexes. Build a trie of every suffix of one text, compress its single-child chains, and you have a suffix tree; sort the suffixes instead and you have a suffix array. Both answer "does this pattern occur in the text?" without scanning the text: in time proportional to the pattern's length for a suffix tree, and that times log⁡n\log n for a suffix array.

Recognizing it, and what comes next

Look for these signals in a problem statement:

  • "Seen before?", counting, duplicates, pairs with a given sum in unsorted data, grouping by a key: a hash map or hash set, O(1)O(1) expected per operation, so one pass over the input instead of comparing all pairs.
  • "Find this pattern in that text", all occurrences, repeated blocks: string matching with KMP, the Z-function or a rolling hash, in O(n+m)O(n + m).
  • Prefixes: autocomplete, "how many words start with…", longest common prefix: a trie, O(L)O(L) per word.
  • Many questions about the substrings of one fixed text: a suffix array or a suffix tree.
  • Questions about order (the smallest key above xx, all keys in a range): not a hash table, because hashing scrambles order on purpose. Use a sorted array or a balanced search tree.
Check your understanding

You get 10510^5 unsorted integers and a target TT, and must decide whether two of them, at different positions, sum to TT. Which approach fits best?

  1. Check every pair
  2. A trie of the numbers' decimal digits
  3. One pass with a hash set: for each xx, check whether T−xT - x has been seen, then add xx
  4. Rabin–Karp on the numbers written out as one long string
Show the answer

C. One pass with a hash set: for each xx, check whether T−xT - x has been seen, then add xx

Each xx needs a partner T−xT - x among the earlier numbers, and "have I seen this before?" is exactly what a hash set answers in O(1)O(1) expected time: O(n)O(n) for the whole list. Sorting and walking two pointers inward also works, in O(nlog⁡n)O(n \log n).

Optimized lessonWhat you will do there
Hash TablesHash functions for numbers and strings, the proof that chains have expected length 1+α1 + \alpha, Knuth's formulas for open addressing, deletion with tombstones, resizing, and what Python, C++ and Java really do.
Universal Hashing & SketchesDraw hash functions at random with a guarantee on every input, and summarize huge data sets with Bloom filters, Count-Min sketches and HyperLogLog.
String Matching: Rabin–Karp, KMP & the Z-FunctionThree linear-time matchers with their correctness proofs, and the borders and periods of strings behind them.
TriesInsert, search, autocomplete and delete in O(L)O(L), memory trade-offs, and binary tries for maximum-XOR problems.
Suffix Arrays & Suffix TreesSort every suffix of a text to answer substring questions: pattern search, distinct substrings and the longest repeated substring.
In the Optimized lessons each tool gets its algorithm, its proof of correctness and its exact cost.

Key takeaways

  • A hash function turns a key into a slot index, so a hash table finds a key by computing where it should be: O(1)O(1) time per operation on average.
  • Collisions are unavoidable (pigeonhole) and arrive early (birthday paradox: even odds after about 1.18m1.18\sqrt m keys). Chaining keeps a list per slot; open addressing probes other slots.
  • Costs grow with the load factor α=n/m\alpha = n/m, so tables double and rehash when α\alpha passes a threshold, which keeps insertions O(1)O(1) amortized.
  • "O(1)O(1) on average" is not a worst-case promise: against a fixed, public hash function an adversary can make nn insertions cost Θ(n2)\Theta(n^2). Random or secretly keyed hash functions defend against it.
  • Rolling hashes turn substring comparisons into number comparisons (Rabin–Karp), KMP matches without moving backward in the text, and tries answer prefix questions in time proportional to the length of the word.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A hash table has 1,000 slots and a hash function that scatters keys like random numbers. About how many keys can you insert before a collision becomes more likely than not?

  1. About 10
  2. About 40
  3. About 500
  4. Exactly 1,001, by the pigeonhole principle
Show the answer

B. About 40

By the birthday paradox, collisions become likely after about 1.18m1.18\sqrt m keys. For m=1000m = 1000 the chance passes 50% at the 38th key, when the table is less than 4% full. The pigeonhole principle only guarantees a collision at 1,001 keys.

Question 2

A table uses linear probing. Keys A and B both hash to slot 4; A sits in slot 4, and B, inserted later, moved on to slot 5. You delete A by simply emptying slot 4. What goes wrong?

  1. Nothing: B is still stored in slot 5
  2. B automatically moves back into slot 4
  3. A lookup for B starts at slot 4, finds it empty, and wrongly reports that B is absent
  4. The load factor can no longer be computed
Show the answer

C. A lookup for B starts at slot 4, finds it empty, and wrongly reports that B is absent

A lookup follows the probe sequence from h(B)=4h(B) = 4 and stops at the first empty slot, which is now slot 4. Real tables mark a deleted slot with a tombstone instead: lookups step over it, and later insertions can reuse it.

Question 3

A web server reads 10510^5 form fields into a chained hash table whose hash function is fixed and public. An attacker chooses field names that all land in the same slot. About how many key comparisons do the insertions make, if each insertion first scans the chain for a duplicate?

  1. About 10510^5
  2. About 1.7×1061.7 \times 10^6
  3. About 5×1095 \times 10^9
  4. About 101510^{15}
Show the answer

C. About 5×1095 \times 10^9

The ii-th insertion scans the i−1i - 1 keys already in the chain: 0+1+⋯+(n−1)=n(n−1)/2≈5×1090 + 1 + \dots + (n - 1) = n(n-1)/2 \approx 5 \times 10^9 comparisons, seconds of work at least, where well-spread keys would need about 10510^5.

Question 4

Rabin–Karp finds a window of the text whose hash equals the pattern's hash. What does it do next?

  1. It reports an occurrence immediately
  2. It recomputes both hashes with a different modulus
  3. It compares the window with the pattern character by character, and reports an occurrence only if they agree
  4. It jumps ahead by the length of the pattern
Show the answer

C. It compares the window with the pattern character by character, and reports an occurrence only if they agree

Different strings can share a hash, so equal hashes only make a match likely. A character-by-character check rules out a spurious hit. With a large random modulus spurious hits are rare, so the check is almost always spent on real occurrences.

Question 5

An app stores 50,000 product names and, as the user types, must list every name that starts with the letters typed so far. Which structure fits best?

  1. A trie of the product names
  2. A hash set of the product names
  3. Rabin–Karp, searching for the typed letters in all the names joined into one long text
  4. A hash map from each name's length to the names of that length
Show the answer

A. A trie of the product names

In a trie, the names that start with the typed prefix are exactly the words below the prefix's node. Walking down costs one step per typed letter, plus the size of the list that is shown.

Go deeper

Further reading

  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapters 11 (hash tables) and 32 (string matching).
  • R. Sedgewick & K. Wayne, Algorithms, 4th ed. (Addison-Wesley, 2011), section 3.4 (hash tables) and chapter 5 (strings).