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 " on average" promises for Python's
dict, C++'sunordered_mapand Java'sHashMap, 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 comparisons, so asking it for each of items costs about : for a million items, half a trillion comparisons. Sorting the keys and using binary search brings one question down to about 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 maps every key to one of slots of an array. To insert a key, compute and store the key in that slot. To look it up later, compute again and look in that one slot. Nothing is searched.
For whole numbers the simplest hash function is the remainder, . With slots, the key 57 goes to slot , 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.
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 pairs, and every pair is a chance to match. In general, with slots a collision becomes more likely than not after about 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:
| Strategy | Where colliding keys go | How a lookup works |
|---|---|---|
| Chaining | Each slot holds a list (a chain) of every key that hashed there | Compute the slot, then scan its chain |
| Open addressing | One key per slot. A key whose slot is taken tries other slots in a fixed order, its probe sequence, until it finds a free one | Follow the same probe sequence until you meet the key or an empty slot |
Load factor and resizing
How full a table is matters more than how big it is. The load factor counts keys per slot: with chaining, the average chain holds keys. With linear probing, clusters grow much faster than as the table fills. If the hash function scatters keys like random numbers, the expected costs are:
| Load factor | Chaining: keys compared to find a stored key | Linear probing: probes to find a stored key | Linear probing: probes to learn a key is absent |
|---|---|---|---|
| 50% | 1.25 | 1.5 | 2.5 |
| 75% | 1.375 | 2.5 | 8.5 |
| 90% | 1.45 | 5.5 | 50.5 |
So real tables never let 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 every key's slot changes. That one insertion costs , but it happens so rarely that the average cost per insertion stays , 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 insertions cost 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.
You insert 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?
- Every insertion takes time
- The insertions take time in total on average, although a few of them take each
- Insertions keep getting slower as the table grows, because every rehash copies more keys
- The table would be faster if it never resized and simply let its chains grow
Show the answer
B. The insertions take time in total on average, although a few of them take each
A resize copies every key, so that one insertion costs . But resizes happen at sizes that double, so the copying adds up to less than in total: amortized per insertion, on top of the expected for the insertion itself.
Fingerprints for strings
Hashing works on text too. Comparing two strings of length character by character costs up to 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 of length in a text of length , the problem of pattern matching. The naive method tries every alignment and compares character by character: up to comparisons. Rabin–Karp compares the fingerprint of each length- 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 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:
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 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 comparisons, and with a large, randomly chosen prime it is almost never wasted: the expected running time is plus 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 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 walks down 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 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, 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 .
- Prefixes: autocomplete, "how many words start with…", longest common prefix: a trie, 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 , all keys in a range): not a hash table, because hashing scrambles order on purpose. Use a sorted array or a balanced search tree.
You get unsorted integers and a target , and must decide whether two of them, at different positions, sum to . Which approach fits best?
- Check every pair
- A trie of the numbers' decimal digits
- One pass with a hash set: for each , check whether has been seen, then add
- Rabin–Karp on the numbers written out as one long string
Show the answer
C. One pass with a hash set: for each , check whether has been seen, then add
Each needs a partner among the earlier numbers, and "have I seen this before?" is exactly what a hash set answers in expected time: for the whole list. Sorting and walking two pointers inward also works, in .
| Optimized lesson | What you will do there |
|---|---|
| Hash Tables | Hash functions for numbers and strings, the proof that chains have expected length , Knuth's formulas for open addressing, deletion with tombstones, resizing, and what Python, C++ and Java really do. |
| Universal Hashing & Sketches | Draw 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-Function | Three linear-time matchers with their correctness proofs, and the borders and periods of strings behind them. |
| Tries | Insert, search, autocomplete and delete in , memory trade-offs, and binary tries for maximum-XOR problems. |
| Suffix Arrays & Suffix Trees | Sort every suffix of a text to answer substring questions: pattern search, distinct substrings and the longest repeated substring. |
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: time per operation on average.
- Collisions are unavoidable (pigeonhole) and arrive early (birthday paradox: even odds after about keys). Chaining keeps a list per slot; open addressing probes other slots.
- Costs grow with the load factor , so tables double and rehash when passes a threshold, which keeps insertions amortized.
- " on average" is not a worst-case promise: against a fixed, public hash function an adversary can make insertions cost . 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.
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?
- About 10
- About 40
- About 500
- Exactly 1,001, by the pigeonhole principle
Show the answer
B. About 40
By the birthday paradox, collisions become likely after about keys. For 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.
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?
- Nothing: B is still stored in slot 5
- B automatically moves back into slot 4
- A lookup for B starts at slot 4, finds it empty, and wrongly reports that B is absent
- 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 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.
A web server reads 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?
- About
- About
- About
- About
Show the answer
C. About
The -th insertion scans the keys already in the chain: comparisons, seconds of work at least, where well-spread keys would need about .
Rabin–Karp finds a window of the text whose hash equals the pattern's hash. What does it do next?
- It reports an occurrence immediately
- It recomputes both hashes with a different modulus
- It compares the window with the pattern character by character, and reports an occurrence only if they agree
- 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.
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?
- A trie of the product names
- A hash set of the product names
- Rabin–Karp, searching for the typed letters in all the names joined into one long text
- 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
- Hash Tables · Hash functions, collisions, chaining and open addressing.
- Universal Hashing & Sketches · Random hash functions with guarantees, and the data summaries built from them.
- String Matching: Rabin–Karp, KMP & the Z-Function · Finding a pattern in a text without rescanning it.
- Tries · Prefix trees for dictionaries, autocomplete and bitwise queries.
- Suffix Arrays & Suffix Trees · Index every suffix to answer substring questions fast.
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).