Spelling Correction and Phonetic Matching

Matching query terms that are misspelled or spelled differently from the documents. Edit distance and its dynamic-programming computation, k-gram indexes for finding candidates, context-sensitive correction, the noisy channel model, and Soundex.

A spelling corrector chooses, among dictionary terms, the one nearest to what was typed and, among equally near terms, the most frequent. Nearness is edit distance, computed by the dynamic program $D[i][j] = \min(D[i-1][j] + 1,\ D[i][j-1] + 1,\ D[i-1][j-1] + [a_i \ne b_j])$ in time proportional to the product of the lengths; Damerau's variant counts an adjacent transposition as one edit. A bigram index with a Jaccard threshold supplies candidates cheaply but can miss short words and transpositions. On Reuters-21578, 21 of the filter's 33 candidates for bord lie one edit away, and only frequency picks board. A simple noisy channel corrects goverment (8 occurrences) to government (1,730) only if the assumed error rate per edit exceeds about 0.0046. Soundex matches names by sound, never across different first letters.

Suppose the thesis student, searching the four Arctic sentences, types artic climate. The index's dictionary holds arctic, from d1, d2, and d4, but not artic, so the first query word matches nothing. A user who types retreival against a dictionary that holds retrieval has the same problem. The Reuters-21578 stories add a harder case. The misspelling goverment occurs 8 times in the collection, so it is in the dictionary, beside government with 1,730 occurrences. How can a system decide, quickly and from the dictionary alone, which word the user meant? It prefers the dictionary word nearest to what was typed, and among equally near words the most frequent one.

Spelling correction is that decision. Retreival and retrieval differ by two swapped letters. Measured by the standard edit distance, they are two operations apart, or one if swapping two adjacent letters counts as a single operation. The task is to settle on retrieval quickly, without proposing retrial or reversal. A related problem arises with names. Muller and Mueller, or Chebyshev and Tchebycheff, are the same name spelled differently, and matching them requires knowing how they sound rather than how they are written.

These techniques belong with text processing because they extend normalization to cases rules cannot anticipate. They usually operate at query time, comparing query terms with the index's dictionary rather than changing the index. This article follows Manning, Raghavan, and Schütze (2008, §§3.3–3.4).

Here is the route. First come two principles behind every corrector. Then we derive edit distance and its table. Next a k-gram index makes the search fast, tried on the Reuters vocabulary. Then context and a probability model decide goverment. Finally we match names by sound with Soundex.

Two principles

Correction rests on two principles:

  1. Prefer the nearest alternative. Among dictionary terms, choose those closest to what was typed, by some measure of distance between strings.
  2. Among equally near alternatives, prefer the more common one. If board and bored are both one edit from bord, choose the one that occurs more often, in the collection or in the query log. A query log reflects what people actually search for, but it can underrepresent rare and specialized terms.

These principles give a strict order, distance first and frequency second. The noisy channel model described below combines the two into one probability, so a slightly farther but much more likely word can win. A system can also correct a term even when it is in the dictionary, since a valid word can still be the wrong one. Context-sensitive correction, below, deals with such cases.

Both principles need a precise way to say how near two strings are.

Edit distance

The edit distance, or Levenshtein distance (Levenshtein, 1966), between two strings is the minimum number of single-character insertions, deletions, and substitutions that transform one into the other. Cat and cut are at distance 1 (one substitution). Kitten and sitting are at distance 3: substitute s for k, substitute i for e, and insert g.

Example (the student's typo). The edit distance from the student's artic to arctic is 1: one insertion, the missing c. No shorter sequence exists, since the strings differ.

Here is the idea in one sentence. The cheapest edit sequence for two whole strings ends with one of three possible last moves, so its cost follows from the costs for shorter prefixes, which can be computed first.

The formal version. The distance is computed by dynamic programming. Let $D[i][j]$ be the distance between the first $i$ characters of string $a$ and the first $j$ characters of string $b$. Then $D[i][0] = i$, $D[0][j] = j$, and

$$D[i][j] = \min \begin{cases} D[i-1][j] + 1 & \text{(delete } a_i\text{)} \\ D[i][j-1] + 1 & \text{(insert } b_j\text{)} \\ D[i-1][j-1] + [a_i \ne b_j] & \text{(substitute, free if equal)} \end{cases}$$

where $[a_i \ne b_j]$ is 1 if the characters differ and 0 if they are equal.

Why the recurrence is correct. An edit sequence may change the same position several times and in any order, so "the last operation" of a sequence is not obviously an operation on the last characters. The proof therefore goes in two steps. First, the distance equals the cost of the cheapest alignment of the two strings. Second, cheapest alignments obey the recurrence. The dynamic program is the one published by Wagner and Fischer (1974).

An alignment of $a$ and $b$ is a sequence of columns of three kinds: a pair $(a_i, b_j)$, a character of $a$ alone $(a_i, -)$, or a character of $b$ alone $(-, b_j)$. Reading the top entries from left to right must give $a$, and reading the bottom entries must give $b$. The cost of an alignment is the number of its columns that are not a pair of equal characters. For kitten and sitting, this alignment has cost 3, from its first, fifth and seventh columns:

k i t t e n -
s i t t i n g

Lemma. The edit distance between $a$ and $b$ is the least cost of an alignment of $a$ and $b$.

Proof. The distance is at most the least cost. An alignment of cost $c$ gives $c$ edits that turn $a$ into $b$: working through the columns from left to right, delete the character of each column $(a_i, -)$, insert the character of each column $(-, b_j)$, and substitute $b_j$ for $a_i$ in each pair of unequal characters. Pairs of equal characters need no edit.

The least cost is at most the distance. We show by induction on $k$ that if $k$ edits turn $a$ into $b$, then some alignment of $a$ and $b$ has cost at most $k$. For $k = 0$ the strings are equal, and pairing each character with itself costs 0. For $k \ge 1$, let the first edit turn $a$ into $a'$. The other $k - 1$ edits turn $a'$ into $b$, so by the induction hypothesis there is an alignment $A'$ of $a'$ and $b$ of cost at most $k - 1$. Change $A'$ into an alignment of $a$ and $b$ according to the first edit:

  • The edit substituted a character at position $p$. Then $a$ and $a'$ differ only there. Replace the top entry $a'_p$ of its column by $a_p$. If the column was $(a'_p, -)$ its cost is unchanged, and if it was a pair its cost changes by at most 1.
  • The edit deleted $a_p$. Then $a'$ is $a$ without that character. Add a column $(a_p, -)$ to $A'$ immediately before the column that holds the next character of $a$, or at the end if there is none. The top row now reads $a$, and the cost rises by 1.
  • The edit inserted a character, which is $a'_p$. Find its column in $A'$. If the column is $(a'_p, -)$, remove it, and the cost falls by 1. If it is a pair $(a'_p, b_j)$, replace it by $(-, b_j)$, which costs 1 where the pair cost 0 or 1.

In each case the top row reads $a$, the bottom row still reads $b$, and the cost is at most $(k - 1) + 1 = k$. $\blacksquare$

Theorem. The table defined by $D[i][0] = i$, $D[0][j] = j$ and the recurrence above holds, in $D[i][j]$, the edit distance between $a_1 \dots a_i$ and $b_1 \dots b_j$.

Proof. By the lemma it is enough to show that the least alignment cost of the two prefixes, call it $C[i][j]$, satisfies the same boundary values and recurrence. An alignment of $a_1 \dots a_i$ with the empty string consists of $i$ columns $(a, -)$, so $C[i][0] = i$, and in the same way $C[0][j] = j$. Now let $i, j \ge 1$ and look at the last column of an alignment of $a_1 \dots a_i$ and $b_1 \dots b_j$. Because the rows read the strings in order, there are three cases:

  • The last column is $(a_i, -)$, so $a_i$ is deleted. The other columns align $a_1 \dots a_{i-1}$ with all of $b_1 \dots b_j$, at a cost of at least $C[i-1][j]$, and the last column adds one.
  • The last column is $(-, b_j)$, so $b_j$ is inserted. The other columns align $a_1 \dots a_i$ with $b_1 \dots b_{j-1}$, at a cost of at least $C[i][j-1]$, plus one.
  • The last column is the pair $(a_i, b_j)$. The other columns align $a_1 \dots a_{i-1}$ with $b_1 \dots b_{j-1}$, at a cost of at least $C[i-1][j-1]$. The pair is free if the characters are equal and costs one substitution if not.

So every alignment costs at least the minimum of the three expressions in the recurrence. Conversely, a cheapest alignment of the shorter prefixes in any of the three cases, with the matching last column added, is an alignment of $a_1 \dots a_i$ and $b_1 \dots b_j$ with exactly that cost. Hence $C[i][j]$ is that minimum. $C$ and $D$ have the same boundary values and the same recurrence, so they are equal in every cell, by induction on $i + j$. $\blacksquare$

Each cell depends only on the cells above, to the left, and diagonally above-left. Filling the table row by row, left to right, therefore always has the needed values ready. As a check that does not use the proof, the script compares the table with a breadth-first search over single edits for every pair of strings of length up to three over a two-letter alphabet, and the two agree.

For kitten and sitting:

s i t t i n g
0 1 2 3 4 5 6 7
k 1 1 2 3 4 5 6 7
i 2 2 1 2 3 4 5 6
t 3 3 2 1 2 3 4 5
t 4 4 3 2 1 2 3 4
e 5 5 4 3 2 2 3 4
n 6 6 5 4 3 3 2 3

The bottom-right cell gives the distance, 3. The computation fills a table of $(|a|+1)(|b|+1)$ cells, so it takes time proportional to the product of the lengths.

Take one cell to see the rule at work. The cell for kitte against sitti (row e, column for the second i) holds 2. Its three neighbors are 2 above (kitt against sitti), 2 to the left (kitte against sitt), and 1 diagonally (kitt against sitt). Since e and i differ, the candidates are $2 + 1$, $2 + 1$, and $1 + 1$, and the minimum is 2.

The table also records how to achieve the distance. Starting at the bottom-right cell and repeatedly stepping back to a neighbor that produced its value recovers an optimal sequence of edits, a backtrace. For kitten, the path runs along the diagonal from the top-left corner to row n, column n, and then one step right. Along the diagonal the value increases twice, at k against s and at e against i, which are the two substitutions. The final rightward step from 2 to 3 is the insertion of g. Spelling correction usually needs only the distance. The alignment explains to a reader, or to a weighted error model, which edits were made.

The figure below shows the tables for retreival. With Levenshtein distance, the swapped e and i cost two substitutions. With transpositions allowed, as described next, the same swap costs one.

Edit-distance tables for the typed retreival, down the rows, against retrieval, across the columns, with the cells of an optimal path highlighted. On the left, plain Levenshtein distance: follow the path down the diagonal and notice that the value rises twice, at the two letters that are out of place, for a distance of 2. On the right, transpositions are allowed: at the dashed cell the path jumps two rows and two columns at a cost of one, for a distance of 1.
Edit-distance tables for the typed retreival, down the rows, against retrieval, across the columns, with the cells of an optimal path highlighted. On the left, plain Levenshtein distance: follow the path down the diagonal and notice that the value rises twice, at the two letters that are out of place, for a distance of 2. On the right, transpositions are allowed: at the dashed cell the path jumps two rows and two columns at a cost of one, for a distance of 1.

Transpositions and weights

Two refinements are common. Damerau–Levenshtein distance also counts the transposition of two adjacent characters as a single operation (Damerau, 1964), since swapped letters are among the most common typing errors. Under it, retreival is at distance 1 from retrieval rather than 2.

The restricted version described below needs one more case in the recurrence. When $a_{i-1} a_i = b_j b_{j-1}$, meaning the two characters are swapped, $D[i][j]$ may also be $D[i-2][j-2] + 1$. In the right-hand table above, that case applies at row i, column e. There ei in the typed string is ie reversed, so the cell takes $D[4][4] + 1 = 0 + 1 = 1$ instead of the 2 that substitutions give.

Two versions are in use. The restricted version, also called optimal string alignment, never edits a substring more than once. It can therefore give a larger distance than the unrestricted one: ca and abc are at distance 3 under the restricted version and 2 under the unrestricted one.

Example (ca and abc). Two edits turn ca into abc when a transposed pair may be edited again: transpose ca into ac, then insert b between the two letters. The second edit changes the substring the first one produced, and the extra case of the recurrence cannot express that. The case applies only when the last two characters of one prefix are the last two of the other in reverse order, and it then steps back two rows and two columns at once, with no room for a character between the swapped pair. For ca against abc the case never applies: the adjacent pairs of abc are ab and bc, and neither is ac, the reverse of ca. The restricted table is therefore the plain Levenshtein table:

a b c
0 1 2 3
c 1 1 2 2
a 2 1 2 3

Its distance is 3: for instance insert a, substitute b for c, and substitute c for a. The unrestricted distance of 2 is computed in the script by a dynamic program that keeps, for each character, the last row in which it occurred, and so allows a transposition across characters inserted or deleted between the pair; Lowrance and Wagner (1975) is the reference for the unrestricted problem. A breadth-first search over the four kinds of edit, also in the script, gives the same 2. On every pair of strings of length up to three over two letters, the script confirms that the unrestricted distance is at most the restricted one, which is at most the Levenshtein distance.

Weighted edit distance assigns different costs to different operations. Substituting a letter with one next to it on the keyboard can cost less than substituting a distant one: replacing s by a, its neighbor, costs less than replacing it by p. Manning, Raghavan, and Schütze (2008, §3.3.3) give this example and report that weights set by the likelihood of such substitutions are very effective in practice. The measure then reflects which errors people actually make.

Fill an edit-distance table one cell at a time. Each step shows the three neighbors the new cell is computed from (and, with transpositions allowed, the cell two rows and two columns back), and the readout gives the arithmetic. When the table is full, an optimal path is shaded. Try retreival with and without transpositions, and notice that ca and abc stay at distance 3, because the restricted transposition rule cannot help.

Finding candidates with a k-gram index

Edit distance says how near two strings are, but not where to look. Computing the edit distance from a query term to every term in a dictionary of millions is too slow. The usual solution is a cheap filter that finds a small set of plausible candidates first.

A k-gram index maps each sequence of $k$ characters to the dictionary terms that contain it. With $k = 2$ and $ marking the start and end of a word, the term board contains the bigrams $b, bo, oa, ar, rd, and d$. To correct bord, take its bigrams, $b, bo, or, rd, and d$, and retrieve the terms that share many of them. The overlap is measured with the Jaccard coefficient, the size of the intersection divided by the size of the union:

Candidate Shared bigrams Union Jaccard
board $b bo rd d$ 7 0.571
bored $b bo or d$ 7 0.571
border $b bo or rd 8 0.500
lord or rd d$ 7 0.429
boardroom $b bo rd 12 0.250
abroad d$ 11 0.091

The first row, in full. The bigram set of bord has 5 members, and that of board, $b, bo, oa, ar, rd, d$, has 6. They share 4. The union needs no second pass over the sets, since $|A \cup B| = |A| + |B| - |A \cap B| = 5 + 6 - 4 = 7$. The coefficient is $4/7 = 0.571$. A scan of the k-gram index's postings can therefore compute every coefficient from a count of shared k-grams and the two set sizes (Manning, Raghavan, and Schütze, 2008, §3.3.4). The other rows follow the same arithmetic: $4/(5 + 6 - 4)$ for bored, $4/(5 + 7 - 4)$ for border, $3/(5 + 5 - 3)$ for lord, $3/(5 + 10 - 3)$ for boardroom, and $1/(5 + 7 - 1)$ for abroad.

The filter then runs to its end in three steps.

  1. Threshold. Terms with a coefficient of at least 0.4, say, are kept: board, bored, border and lord. Boardroom (0.250) and abroad (0.091) are dropped without any edit distance being computed.
  2. Edit distance. Only the four survivors are compared with bord. Board, bored, and lord are at distance 1, and border is at distance 2, so the first principle drops border.
  3. Frequency. The tie among board, bored, and lord is broken by the second principle. In Reuters-21578, board occurs 1,159 times and lord 28 times, and bored does not occur. The correction is board.

The threshold is a heuristic, not a guarantee. A correct term that shares few k-grams with the typo, as often happens with short words, falls below it and is never considered. The k-gram index is built once, from the dictionary, and it is small, because it indexes terms rather than documents.

The same index also answers wildcard queries such as bo*d, by intersecting the postings of the k-grams the pattern requires and then checking each candidate against the pattern itself. Wildcard Queries works that use in full, beside the permuterm index.

On the Reuters dictionary

The table above uses a handful of hand-picked words. A real dictionary is less tidy. Take the vocabulary of Reuters-21578 (Lewis, 1997): 29,187 terms from 10,788 news stories, lowercased and split into runs of letters as in term statistics. In its bigram index, 6,031 terms share at least one bigram with bord. Of those, 33 have a Jaccard coefficient of at least 0.4. The highest-scoring ones:

Candidate Jaccard Edit distance Collection frequency
borad 0.571 1 1
board 0.571 1 1,159
baord 0.571 1 1
ord 0.500 1 1
brd 0.500 1 1
bor 0.500 1 17
border 0.500 2 31
borden 0.500 2 9
boasrd 0.500 2 1

Two of the three best candidates, borad and baord, are themselves typing errors that occur once each in the newswire. Ord, brd, and bor are fragments and abbreviations. All five tie with board on distance, and so do fifteen more of the 33 survivors, among them bond (260 occurrences), borg (140), ford (46) and lord (28), which sit just below the table at a coefficient of $3/7 = 0.429$. In all, 21 survivors are one edit from bord. Only frequency, the second principle, separates them: board occurs 1,159 times, more than four times as often as its most frequent rival, bond, and the misspellings and fragments in the table at most 17 times each. Any dictionary built from real text contains its own misspellings, as the long tail of hapax legomena showed. That is why frequency, not mere membership in the dictionary, is the evidence that a word is correct.

Example (a transposition at the threshold). The typo exprot is one transposition away from export, which occurs 1,067 times in Reuters, and export passes a Jaccard threshold of 0.4 only just. The two words have seven bigrams each and share four, $e, ex, xp, and t$. The coefficient is $4/(7 + 7 - 4) = 0.4$ exactly, because swapping two letters breaks three bigrams at once. With a slightly stricter threshold, export would never reach the edit-distance stage. Short words and transposed letters are where k-gram filters most often lose the right answer.

Context-sensitive correction

Every method so far looks at one word at a time. Isolated-term correction therefore cannot fix an error that produces a real word. In flew form Heathrow, every word is correctly spelled, and the error is that form should be from (Manning, Raghavan, and Schütze, 2008, §3.3.5). Correcting it requires context. Among the variants of each query word, the system finds the combination that is most common as a phrase in the collection or the query log. Flew from Heathrow is far more frequent than flew form Heathrow.

Example (context decides, counted on Reuters). For the two-word query fell form, phrase counts in Reuters-21578 choose fell from. Both typed words are in the dictionary, and form occurs 183 times, so isolated-term correction leaves the query alone. Take as variants of each word the dictionary terms within one edit of it, counting a transposition as one edit and including the word itself. Fell has 18 variants and form has 19, which gives $18 \times 19 = 342$ candidate phrases. Counting each as a pair of adjacent words in the collection: the typed fell form never occurs, fell from occurs 15 times, and the next most frequent candidates are well for (8), sell for (6) and fall from (6). Only 9 of the 342 occur at all. The most frequent phrase, fell from, changes one word by one transposition, and it is the correction. The count of candidate phrases is the product of the variant counts, which is why longer queries need the pruning described in the worked problems below.

The noisy channel model gives this reasoning a probabilistic form. Kernighan, Church, and Gale (1990) applied it to isolated misspelled words. With a language model over phrases rather than single words, the same formula takes context into account. Here is the idea in one sentence: prefer the intended word that is both likely in itself and likely to have been mistyped as what we see.

Treat the typed query $q$ as the output of a noisy channel applied to an intended query $w$, and choose the $w$ that maximizes

$$P(w \mid q) \propto P(q \mid w)\, P(w).$$

The two factors are separate models:

  • $P(w)$, the language model, measures how likely the intended query is. It is estimated from query logs or text.
  • $P(q \mid w)$, the error model, measures how likely the typed string is as a corruption of the intended one. It is estimated from observed pairs of errors and corrections.

Brill and Moore (2000) improved the error model by allowing edits of multi-character substrings, such as ph typed as f. Web search engines can estimate both models from their query logs, as the web search article describes. That lets them correct names and new terms that no fixed dictionary contains, once enough users have searched for them.

A worked noisy-channel example

The formula's behavior is easiest to see with deliberately simple models:

  • For the language model, take each word's share of the Reuters-21578 text, $P(w) = \mathit{cf}_w / T$, where $\mathit{cf}_w$ is the word's collection frequency and $T$ the total number of tokens.
  • For the error model, assume that each edit happens independently with a small probability $\varepsilon$. Then $P(q \mid w) = \varepsilon^{d(q, w)}$, where $d$ is the edit distance, and an intended word is typed correctly, $d = 0$, with probability about 1.

Real error models are learned and give different edits different probabilities. This one has a single parameter, the typist's error rate.

Back to goverment, the misspelling from the opening. It makes a good test because it occurs 8 times in the collection and so is in the dictionary. Its main rival is government, with 1,730 occurrences, one edit away. The posterior odds between them are

$$\frac{P(\textit{government} \mid q)}{P(\textit{goverment} \mid q)} = \frac{\varepsilon^{1} \times 1730}{\varepsilon^{0} \times 8} = 216.25\,\varepsilon.$$

The correction wins when this exceeds 1, that is, when $\varepsilon > 1/216.25 \approx 0.0046$.

Example (an error rate of one in a thousand). If typists make an error on one edit in a thousand, $\varepsilon = 0.001$, then goverment is not corrected. The odds are $216.25 \times 0.001 \approx 0.22$, below 1, so the word as typed wins. Normalizing over all the dictionary terms within two edits of the query gives the probabilities for this rate and for a ten times higher one:

Assumed error rate $\varepsilon$ $P(\textit{government} \mid q)$ $P(\textit{goverment} \mid q)$ Choice
0.01 0.683 0.316 government
0.001 0.178 0.822 goverment

(Probabilities rounded to three decimals; other candidates share the remaining 0.001 or less.) The same typed string is corrected under one assumption about how often people mistype and left alone under the other. The two principles at the start of the article expressed this trade-off as a strict order. The noisy channel turns it into a threshold that can be estimated from data, by measuring how often real users mistype.

Phonetic matching and Soundex

Edit distance compares letters. Names are often misspelled in ways that preserve their sound instead: Smith and Smyth, Herman and Hermann. Phonetic algorithms map strings to codes intended to give names that sound alike the same code. The match is approximate: similar-sounding names can receive different codes, and different names can share one. The oldest is Soundex, patented by Robert Russell in 1918 (Russell, 1918) and used for decades to index United States census records (National Archives and Records Administration, "The Soundex indexing system"). The common American version works as follows:

  1. Keep the first letter.
  2. Replace the remaining letters with digits: b, f, p, v → 1; c, g, j, k, q, s, x, z → 2; d, t → 3; l → 4; m, n → 5; r → 6. Vowels, h, w, and y get no digit.
  3. Merge adjacent letters with the same digit into one, including when they are separated only by h or w. A vowel between them keeps them separate. A letter with the same digit as the first letter is also merged into it.
  4. Keep the first letter and the first three digits, padding with zeros if necessary.

Example (Lee and Leigh). Lee and Leigh do not receive the same code. In Lee, every letter after the L is a vowel, so the code is L000. In Leigh, the g is coded 2, giving L200, although it is silent. Some results, computed with this procedure:

Names Codes
Robert, Rupert R163, R163
Muller, Mueller M460, M460
Smith, Smyth S530, S530
Herman, Hermann H655, H655
Lee, Leigh L000, L200
Chebyshev, Tchebycheff C121, T212

The failures show the algorithm's assumptions. Soundex keeps the first letter, so variants that differ in their first letter, such as Chebyshev and Tchebycheff, can never match. It also knows nothing about silent letters, so the gh in Leigh separates it from Lee. More elaborate algorithms such as Metaphone apply many more pronunciation rules.

Zobel and Dart (1996) compared phonetic matching techniques by recall and precision. Their new techniques were more effective than Soundex and than edit distances, and combining the evidence of several techniques improved the results further. The course text reports their finding that a variant of Soundex performs poorly for general spelling correction (Manning, Raghavan, and Schütze, 2008, §3.5). For retrieval, phonetic matching is mainly useful as an additional source of candidates for name searches, not as a replacement for edit distance.

Where correction fits

Spelling correction usually runs on queries, leaving the index unchanged. Query terms not found in the dictionary, or found only rarely, are checked for close alternatives. This site's own search works this way, with a bigram index over the words its pages use.

How the result is presented is a separate decision. The system can suggest a correction, rerun the query with it and say so, or apply it silently, as described in the web search article. Correction is applied to documents mainly when they contain systematic errors. Text produced by optical character recognition is the main example: the same confusions, such as rn read as m, recur throughout a collection. Kukich (1992) surveys techniques for correcting words in text automatically.

Worked problems

The first four problems are exercises from chapter 3 of the course text (Manning, Raghavan, and Schütze, 2008), restated with their data and solved in our own words. The fifth is posed on this article's Soundex procedure. The script tools/experiments/indexing/spelling.py checks every table and number.

Problem 1 (Exercise 3.8 of the course text). Compute the edit distance between paris and alice, writing down the array of distances between all prefixes.

Solution. The distance is 4. The table has a row for each prefix of paris and a column for each prefix of alice, starting with the empty prefix:

a l i c e
0 1 2 3 4 5
p 1 1 2 3 4 5
a 2 1 2 3 4 5
r 3 2 2 3 4 5
i 4 3 3 2 3 4
s 5 4 4 3 3 4

Two cells show the rule. In row a, column a, the characters are equal, so the diagonal neighbor 1 is copied without cost; the other candidates are $1 + 1$ from above and $2 + 1$ from the left, and the minimum is 1. In row s, column e, the characters differ and the neighbors are 4 above, 3 to the left and 3 diagonally, so the cell is $3 + 1 = 4$.

A backtrace from the bottom-right cell gives one optimal sequence of four edits: delete p, substitute l for r, insert c, substitute e for s. Applied in order, paris becomes aris, alis, alics, alice. As an alignment:

p a r i - s
- a l i c e

Four of its six columns are not pairs of equal characters.

Problem 2 (Exercise 3.7). Show that the edit distance between two strings $s_1$ and $s_2$ is never more than $\max\{|s_1|, |s_2|\}$.

Solution. It is enough to exhibit a sequence of at most that many edits. Suppose first that $|s_1| \le |s_2|$. Substitute, where they differ, the first $|s_1|$ characters of $s_2$ for the characters of $s_1$: at most $|s_1|$ substitutions. Then insert the remaining $|s_2| - |s_1|$ characters of $s_2$ at the end. That is at most $|s_1| + (|s_2| - |s_1|) = |s_2|$ edits. If instead $|s_1| > |s_2|$, substitute within the first $|s_2|$ positions and delete the last $|s_1| - |s_2|$ characters of $s_1$, at most $|s_2| + (|s_1| - |s_2|) = |s_1|$ edits. In both cases the number of edits is at most the longer length, and the distance, being the minimum over all sequences, is no larger. In the table this sequence is the path down the main diagonal and then straight along the last row or column.

The same count gives a lower bound. Each edit changes the length of the string by at most one, so the distance is at least $\big||s_1| - |s_2|\big|$. For paris and alice the two bounds are 0 and 5, and the distance is 4.

Problem 3 (Exercise 3.10). In the text's bigram index for spelling correction, the bigram or has the postings border, lord, morbid and sordid. Compute the Jaccard coefficient between the query bord and each of these terms. The text's figure uses bigrams without boundary markers, so bord has the three bigrams bo, or, rd.

Solution. The coefficients are 0.6, 0.5, 0.143 and 0.333.

Term Bigrams Shared with bord Union Jaccard
border bo, or, rd, de, er bo, or, rd $3 + 5 - 3 = 5$ $3/5 = 0.600$
lord lo, or, rd or, rd $3 + 3 - 2 = 4$ $2/4 = 0.500$
morbid mo, or, rb, bi, id or $3 + 5 - 1 = 7$ $1/7 = 0.143$
sordid so, or, rd, di, id or, rd $3 + 5 - 2 = 6$ $2/6 = 0.333$

With a threshold of 0.4, border and lord go on to the edit-distance step and the other two do not. The coefficients differ from those in this article's table, where border scored 0.500 and lord 0.429, because that table adds the boundary bigrams $b and d$ to bord. Boundary markers reward words that start and end like the query. Border matches $b but not d$, and lord matches d$ but not $b, so each gains one shared bigram and three in the union: $4/8$ and $3/7$.

Problem 4 (Exercise 3.11). The four-term query catched in the rye is to be corrected in context. Isolated-term correction suggests five alternatives for each of the four terms. How many corrected phrases must be considered if every combination is tried?

Solution. $6^4 = 1{,}296$. Each of the four positions has six variants, the original term and its five alternatives, and the choices are independent, so there are $6 \times 6 \times 6 \times 6$ phrases. The count grows as $6^k$ with the number of terms $k$, which is why context-sensitive correctors prune: they extend only the most frequent corrected prefixes, word by word, instead of scoring every combination.

Problem 5. Compute the Soundex codes of Tchebycheff and of Ashcraft, step by step.

Solution. The codes are T212 and A261.

Tchebycheff. Keep the first letter, T. The remaining letters are c, h, e, b, y, c, h, e, f, f. Their digits are c → 2, b → 1, c → 2, f → 1, f → 1, with h, e and y giving none. The first digit, 2, differs from the digit of the first letter (T is 3), so it stays. The two 2s are separated by the vowel e and by b, so both stay. The final two f's are adjacent with the same digit and merge into one 1. The digits are 2, 1, 2, 1, and the first three give T212. The companion spelling Chebyshev starts with C and gives C121, so the two spellings of the same name can never match.

Ashcraft. Keep A. The remaining letters are s, h, c, r, a, f, t, with digits s → 2, c → 2, r → 6, f → 1, t → 3. The s and the c have the same digit and are separated only by h, so by step 3 they merge into one 2. A vowel between them would have kept both. The digits are 2, 6, 1, 3, and the first three give A261.

What we have learned

Spelling correction finds the word a user meant by nearness first, then frequency. Edit distance measures nearness, computed by a dynamic-programming table whose recurrence is the recurrence of cheapest alignments. A bigram index finds candidates fast, at the risk of missing transpositions such as exprot. On Reuters, only frequency separated board from the dictionary's own misspellings. The noisy channel combines both principles, and whether it corrects goverment depends on an assumed error rate. Soundex matches names by sound, within the limits of its first-letter rule.

Text has now become normalized, stemmed terms, and queries can be corrected against them. The k-gram index built here for correction also answers patterns such as bo*d, which is the subject of Wildcard Queries. After that, The Inverted Index establishes the structure that stores the terms so that a query can find, in milliseconds, every document that contains them.

References

  • Brill, E., and Moore, R. C. (2000). An improved error model for noisy channel spelling correction. In Proceedings of ACL 2000, 286–293. record
  • Damerau, F. J. (1964). A technique for computer detection and correction of spelling errors. Communications of the ACM, 7(3), 171–176. record · 2 pages
  • Kernighan, M. D., Church, K. W., and Gale, W. A. (1990). A spelling correction program based on a noisy channel model. In Proceedings of COLING 1990, 205–210. record
  • Kukich, K. (1992). Techniques for automatically correcting words in text. ACM Computing Surveys, 24(4), 377–439. record
  • Levenshtein, V. I. (1966). Binary codes capable of correcting deletions, insertions, and reversals. Soviet Physics Doklady, 10(8), 707–710. record
  • Lewis, D. D. (1997). Reuters-21578 text categorization test collection, distribution 1.0. record · 11 pages
  • Lowrance, R., and Wagner, R. A. (1975). An extension of the string-to-string correction problem. Journal of the ACM, 22(2), 177–183. record
  • Manning, C. D., Raghavan, P., and Schütze, H. (2008). Introduction to Information Retrieval, sections 3.3–3.5. Cambridge University Press. record · 102 pages
  • National Archives and Records Administration. The Soundex indexing system. https://www.archives.gov/research/census/soundex record
  • Russell, R. C. (1918). U.S. Patent 1,261,167. Index. record
  • Wagner, R. A., and Fischer, M. J. (1974). The string-to-string correction problem. Journal of the ACM, 21(1), 168–173. record
  • Zobel, J., and Dart, P. (1996). Phonetic string matching: Lessons from information retrieval. In Proceedings of SIGIR 1996, 166–172. record

Reviewed: verified, 16 Nov 2026 · citations checked, 16 Nov 2026 · editorial review, 23 Nov 2026 · 10 revisions