Docsity

Approximate String Matching with Edit Distance and Neighborhood Searches, Papers of Computer Science

Toggle sidebar
bg1
A Sublinear Algorithm for Approximate Keyword Searching1
Eugene W. Myers2
Abstract. Given a relatively short query string Wof length P, a long subject string Aof length
N, and a threshold D, the approximate keyword search problem is to find all substrings of Athat
align with Wwith not more than Dinsertions, deletions, and mismatches. In typical applica-
tions, such as searching a DNA sequence database, the size of the "database" Ais much larger
than that of the query W, e.g., Nis on the order of millions or billions and Pis a hundred to a
thousand. In this paper we present an algorithm that given a precomputed index of the database
A, finds rare matches in time that is sublinear in N, i.e. Ncfor some c < 1. The sequence A
must be over a finite alphabet Σ. More precisely, our algorithm requires O(DN pow(ε)log N)
expected-time where ε = D/ P is the maximum number of differences as a percentage of query
length and pow(ε) is an increasing and concave function that is 0 when ε= 0. Thus the algo-
rithm is superior to current O(DN) algorithms when εis small enough to guarantee that
pow(ε)<1. As seen in the paper, this is true for a wide range of ε, e.g., εup to 33% for DNA
sequences (| Σ| = 4) and 56% for proteins sequences (| Σ| = 20). In preliminary practical
experiments, the approach gives a 50- to 500-fold improvement over previous algorithms for
problems of interest in molecular biology.
Key Words. Approximate match, Dynamic programming, Index, Word neighborhood
0. Introduction
Given a relatively short query string Wof length P, a long subject string Aof length N, and a
threshold D, the approximate keyword search problem is to find all substrings of Athat align
with Wwith not more than Dinsertions, deletions, and mismatches. More precisely, if δ(V,W)
is the edit distance between Vand W, and if A[i..j] denotes the substring of Aconsisting of its
ith through jth characters, then the problem is to find all pairs i,jsuch that δ(W,A[i..j]) ≤D.
For this problem, we say that the maximum mismatch ratio is ε=D / P and that we are searching
Afor ε-matches to W.
This problem has been much studied. Sellers [Sel80] presented the obvious O(PN) algorithm
as a slight variation of the classic dynamic programming algorithm for the sequence vs.
sequence comparison problem (here we are comparing a sequence vs. substrings of the other).

1This work was supported in part by the National Institutes of Health under Grant R01 LM04960-01 and the Aspen Center for Phy-
sics.
2Department of Computer Science, University of Arizona, Tucson, AZ 85721, U.S.A.
- 1 -
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d

Partial preview of the text

Download Approximate String Matching with Edit Distance and Neighborhood Searches and more Papers Computer Science in PDF only on Docsity!

A Sublinear Algorithm for Approximate Keyword Searching

Eugene W. Myers^2

Abstract. Given a relatively short query string W of length P , a long subject string A of length N , and a threshold D , the approximate keyword search problem is to find all substrings of A that align with W with not more than D insertions, deletions, and mismatches. In typical applica- tions, such as searching a DNA sequence database, the size of the "database" A is much larger than that of the query W , e.g., N is on the order of millions or billions and P is a hundred to a thousand. In this paper we present an algorithm that given a precomputed index of the database A , finds rare matches in time that is sublinear in N , i.e. N c^ for some c < 1. The sequence A must be over a finite alphabet Σ. More precisely, our algorithm requires O ( DN pow (ε)^ log N ) expected-time where ε = D/ P is the maximum number of differences as a percentage of query length and pow (ε) is an increasing and concave function that is 0 when ε = 0. Thus the algo- rithm is superior to current O ( DN ) algorithms when ε is small enough to guarantee that pow (ε) < 1. As seen in the paper, this is true for a wide range of ε, e.g., ε up to 33% for DNA sequences (| Σ| = 4) and 56% for proteins sequences (| Σ| = 20). In preliminary practical experiments, the approach gives a 50- to 500-fold improvement over previous algorithms for problems of interest in molecular biology.

Key Words. Approximate match, Dynamic programming, Index, Word neighborhood

0. Introduction

Given a relatively short query string W of length P , a long subject string A of length N , and a threshold D , the approximate keyword search problem is to find all substrings of A that align with W with not more than D insertions, deletions, and mismatches. More precisely, if δ( V , W ) is the edit distance between V and W , and if A [ i.. j ] denotes the substring of A consisting of its i th^ through j th^ characters, then the problem is to find all pairs i , j such that δ( W , A [ i.. j ]) ≤ D. For this problem, we say that the maximum mismatch ratio is ε = D/ P and that we are searching A for ε -matches to W.

This problem has been much studied. Sellers [Sel80] presented the obvious O ( PN ) algorithm as a slight variation of the classic dynamic programming algorithm for the sequence vs. sequence comparison problem (here we are comparing a sequence vs. substrings of the other).  (^1) This work was supported in part by the National Institutes of Health under Grant R01 LM04960-01 and the Aspen Center for Phy- sics. (^2) Department of Computer Science, University of Arizona, Tucson, AZ 85721, U.S.A.

In roughly the same time frame, Ukkonen and Myers [Ukk85a,MyM86] both reported practical and simple O ( DN ) expected time algorithms. Not long thereafter, Landau and Vishkin [LaV86] arrived at an O ( DN ) worst case algorithm that required O ( N ) space. At about the same time Myers [Mye86a] presented an algorithm with the same worst case time complexity but which required only O ( D^2 ) space. Recently, Galil and Park [GaP89] have reported another O ( DN ) worst-case time algorithm that takes O ( P^2 ) space.

With the advent of applications such as those in molecular biology where the database will be massive, e.g. N in the billions, the need for algorithms that are less than linear in N is becoming of paramount importance. Recently, Chang and Lawler [ChL90] devised a method that takes O ( DN log P/ P ) expected-time when the threshold D is less than P/ (log P + O (1)). It does so by quickly eliminating stretches of the "database" sequence A where a match cannot possibly occur. They term their algorithm sublinear in the sense of Boyer and Moore [BoM77], i.e., cN characters of A are examined where c < 1. Note however, that the algorithm still takes time linear in N and that as P gets larger the stringency of a match must be tightened as ε must be less than 1 / (log P + O (1)).

In this paper we present an algorithm that given a precomputed index of the database A , finds rare matches in time that is truly sublinear in N , i.e. N c^ where c < 1. More precisely, our algo- rithm requires O ( DN pow (ε)^ log N ) expected-time where pow (ε) is an increasing and concave function that is 0 when ε = 0. Thus the algorithm is superior to the O ( DN ) algorithms when ε is small enough to guarantee that pow (ε) < 1. For example pow (ε) is less than one when ε < 33% for | Σ| = 4 (DNA alphabet), and when ε < 56% for | Σ| = 20 (Protein alphabet). Figure 4 on page 9 precisely plots the curve for several choices of | Σ|. Apart from the fact that our algo- rithm is "truly" sublinear, it also has the advantage over the Chang and Lawler algorithm that the degree of sublinearity just depends on ε and not on P. On the other hand, we require a precom- puted O ( N ) space index structure, whereas their method is purely scanning based, requiring only O ( P ) working storage. The bounding argument used in proving the expected complexity of our algorithm is rather crude. Consequently, performance in practice is much superior. In prelim- inary experiments, the approach appears to represent a 100- to 500-fold improvement over the O ( DN ) search algorithms for problems of interest in molecular biology.

1. Overview

In this overview, we sketch the basic concepts and outline the algorithm embodying our result. The various sections of the paper then embellish upon the individual components.

The algorithm assumes that an index for the sequences in the database has already been con- structed. An index for a large text is a data structure that allows one to rapidly find all occurrences of a given query string in the text. In our method, queries will all be of length T = log (^) | Σ| N. Thus, each query can be uniquely encoded as an O ( N ) integer, and we can store the results of all possible queries (which are lists of indices where the corresponding strings of size T appear in A ) in an O ( N ) table. This simple structure can be built in O ( N ) time and 2 N words of space as shown in Section 2.

2 T. This step requires envisioning the result of the word generation lookups as delivering paral- lelogram shaped regions of a dynamic programming matrix or edit graph. All d -matches to a T - word of W are guaranteed to lie in one of these parallelograms. To find matches to 2 T -words it suffices to do a dynamic programming calculation over a 2 T -by-2 d parallelogram about each parallelogram of a T -word ‘‘hit’’. At the k th^ stage of this process, the number of matches is reduced by a factor of 1 /N^2 k (^) (1 − pow (ε))

. Thus while the time to extend matches grows by a fac- tor of 4 at each stage, this is overwhelmed by the reduction in the number of surviving matches. In the end, the total time consumed in expectation is O ( DN pow (ε)^ log N + HDP ) where H is the number of matches to W found.

Note that our algorithm’s expected time complexity is based on the assumption that the data- base is the result of random Bernouilli trials. In this case its expected complexity is O ( DN pow (ε)^ log N ). However, if the database is not random but preconditioned to have H matches to W , then O ( HDP ) time will be spent on each of these matches. Consequently, our algorithm does not improve upon the O ( DN ) algorithm for the sequence-vs.-sequence problem. Nonetheless, for searching problems where the database is large and ‘‘sufficiently’’ random, this algorithm can find near matches with great efficiency and no loss in sensitivity.

2. A Simple Index Data Structure

An index for a large string A = a (^) 1 a (^) 2...^ a (^) N , is a data structure that allows one to efficiently locate all occurrences of a shorter query string within A. In this work, a very simple technique based on integer encodings can be used because all queries are of length O ( log N ) and we assume that the underlying alphabet Σ is fixed and finite. From here on, let T = log (^) | Σ| N and assume all queries are of length between T − D and T + D where D < T.

Consider an arbitrary assignment (bijection) φ of the symbols in Σ to the integers 0 through | Σ| − 1. φ is naturally extended to strings with the recursive definition φ( Wa ) = | Σ| φ( W ) + φ( a ) where W is a string over Σ and a is a symbol in Σ. Essentially φ( W ) is the integer obtained when the string is viewed as a radix-| Σ| number. For n ∈ [0, | Σ| T^ − 1] ⊆ [0, N − 1], let Bucket ( n ) = { i : φ( a (^) i a (^) i + 1...^ a (^) i + T − 1 ) = n }. That is, Bucket ( n ) gives the indices of the leftmost character of each occurrence in A of the unique T -symbol string whose φ-code is n. This simple array of sets is our index structure.

Under the assumption that A is the result of equi-probable Bernouilli trials, one can use Bucket to find all the, say H (^) V , occurrences of a query V within A in O ( T + DH (^) V ) expected time as follows. If V is of length U ≤ T then the leftmost indices of the occurrences of V are exactly the contents of Bucket ( k ) for k ∈ [φ( V )| Σ| T^ −^ U^ ,(φ( V ) + 1)| Σ| T^ −^ U^ − 1]. In this case, it takes time O ( U ) to compute the integers defining the interval of codes and O ( H (^) V ) time to list the H (^) V occurrences of V in A. Thus the total time is less O ( T + DH (^) V ) as claimed. In the case where U is greater than T one knows that the occurrences of V must be a subset of those in Bucket (φ( V (^) T )) where V (^) T denotes the string consisting of the first T symbols of V. It takes O ( T ) time to compute the φ-code, and then it suffices to simply check whether the remaining U − T symbols of V match at each of the locations in the given bucket. While potentially quite

inefficient in the worst case this step works extremely well in the expected case where A is the result of equi-probable Bernouilli trials. Under this assumption the average number of coin- cidental matches to V (^) T is one and on average only 1 / (| Σ| − 1) additional symbols of such coin- cidental matches to V (^) T need be checked before they are discovered not to match V. Thus in expectation only a constant amount of time is spent investigating locations that do not match V. Moreover, O ( U − T ) = O ( D ) time is spent checking additional characters at those locations that do match V. Thus only O ( T + DH (^) V ) expected time is spent in the case where U > T.

Producing the index is also quite simple. First φ (^) i = φ( a (^) i a (^) i + 1...^ a (^) i + T − 1 ) is computed for every index i. This is easily done in an O ( N ) sweep of A using the observation that φ (^) i =

a i | Σ| T^ −^1 + φ i + 1 / | Σ| . Since the numbers φ i are all in the range [0, N − 1], a simple O ( N )

radix sort produces the list Indices = < i (^) 1 , i (^) 2 ,...^ i (^) N > such that φ (^) i (^) j ≤ φ (^) i (^) j + 1. Finally, the array

Header [ n ] = min { j : φ (^) Indices [ j ] = n } is produced in an O ( N ) sweep of Indices. The arrays, Indices and Header , together provide a realization of the Bucket sets. Namely, Bucket ( n ) = { Indices [ j ] : j ∈[ Header [ n ] , Header [ n + 1] − 1 ] }. Thus our index occupies O ( N ) space and takes O ( N ) time to construct.†

In the treatment immediately above two details were overlooked that require attention. First was the statement that T be set to log (^) | Σ| N. T must be an integer, and so in fact one must round the logarithm either up or down. Rounding up implies that as much as O (| Σ| N ) time and space are required to construct the index. Rounding down implies that while only O ( N ) space is used, long queries may take O ( T + | Σ| + DH (^) V ) expected time because the average bucket size can approach | Σ|. If the cardinality of Σ is fairly large (e.g. 20 for protein sequences) then both of

these alternatives are undesirable in practice. A simple repair is to round up, i.e., T =  log | Σ| N  ,

but to use only the first R = log 2 N − log | Σ| N  log 2 | Σ|  bits of the last symbol when com-

puting a code. Specifically, if W is of length T − 1 then the modified encoding ρ of Wa is given by ρ( Wa ) = φ( W )2 R^ + φ( a ) mod 2 R^. The treatment for constructing the index is as before except that φ (^) i is replaced with ρ (^) i = ρ( a (^) i a (^) i + 1...^ a (^) i + T − 1 ). With this choice of encoding, there are no more than N codes and there are no less than N/ 2. Thus the structure takes Θ( N ) time and space to construct independent of the size of Σ, and the average bucket size is between 1 and 2 so that searches using the ρ-code on the first T symbols of a query V will take no more than O ( DH (^) V ) expected time. Note that the T th^ symbol of V will have to be compared against its corresponding symbol for each bucket entry, but this does not add to the asymptotic complexity.

The second detail is that φ (^) i (ρ (^) i ) is not properly defined for i > N − T + 1 ( N − T ). This can rectified by simply adopting the convention that for i > N , a (^) i is any symbol not equal to a (^) N. This guarantees that the integer codes for indices N − T + 2 to N are all distinct and thus contri- bute at most one extra element to any particular Bucket set. Thus the expected case analysis for searching still holds, although one must additionally check each index in a bucket and reject it if it is greater than N − U where U is the length of the query.

†The structure requires exactly 2 N + O (1) integers in the range 0 to N , and may be built with σ( N ) additional space with some very careful ‘‘in-place’’ manipulations. It is thus a very space efficient and practical index.

array L [0.. T + D + 1, 0.. T ] vector V [1.. T + D + 1]

  1. procedure GEN( i )
  2. { for a ∈ Σ do
  3. { L [ i ] ← row ( L [ i − 1] , a )
  4. V [ i ] ← a
  5. if L [ i , T ] ≤ D then
  6. V [1.. i ] is in N (^) D

 ( W ).

  1. else if j

min {L [ i , j ] } ≤ D then

  1. GEN( i + 1)
  2. }
  3. }
  4. L [0] ← < 0, 1, 2,. .. T >
  5. GEN(1) Figure 2: Neighborhood Generator Algorithm The correctness of this procedure requires several observations. First, the smallest entry of row ( R , a ) is never smaller than the smallest entry of R and so it is correct to backtrack when a row is reached for which all entries are greater than D. Second, if a row contains an entry not greater than D then it contains an entry equal to D because successive entries in a row differ by −1, 0, or 1. Moreover, if the largest index of such an entry is j , then adding the suffix W j^ = w (^) j + 1 w (^) j + 1...^ w (^) T gives a word in the neighborhood, and this justifies the decision to search for- ward. Finally, the length of a longest word in the neighborhood is bounded by T + D and so the sizes of L and V are adequate. The algorithm of Figure 2 spends O (| Σ| T ) time per call to GEN and the number of calls is the number of characters in the trie of the neighborhood. The size of the trie is bounded by O ( TZ ) where Z is the number of words in the neighborhood. Thus the algorithm has a worst case complexity of O (| Σ| T^2 Z ). One can do quite a bit better, namely O ( TZ ) time, by better utilizing the information in the matrix rows. Note that as the search progresses forward through the trie one must compute a row whose minimum entry is D before computing a row whose minimum entry is greater than D. Consider the case where such a row is reached and it is further true that the last entry is not D. In this case, the only extensions of the currently generated word that are in the condensed neighborhood are those that perfectly match the appropriate suffixes of W. That is, if the j th^ entry is D , then adding W j^ gives a word whose distance from W is D and this is the only way to get a word this close to W. The one difficulty is that while the word may be in the D -neighborhood, it may not be in the condensed neighborhood. For example, when aba has been generated in the example of Figure 1, the current vector is < 3, 2, 1, 1, 1, 2 > and the possible extensions are the suffixes baa , aa , and a of W = abbaa. But aba  aa is not in the condensed neighborhood as aba  a is. In essence, of the available suffix extensions, one must choose only those that do not have another as a prefix.

This difficulty can be efficiently handled with the failure links of the Knuth-Morris-Pratt con- struction [KMP77] used for exact keyword search. For a word V , let fail (^) V (0) = 0 and for

j ∈ [1, | V | ], let fail (^) V ( j ) = max { k : V (^) k is a su ffix o f V (^) j }. An array recording the values of fail (^) V can be computed in time linear in the length of V. For our problem, let Jump [ T − j ] = T − fail (^) W R^ ( j ) where W R^ is the reverse of W. For index j , the indices Jump [ j ], Jump [ Jump [ j ]], Jump [ Jump [ Jump [ j ]]],...^ are exactly those whose suffix extensions are prefixes of j ’s suffix extension. Thus to check if j ’s extension gives a word in the condensed neighborhood simply requires checking the above sequence until an index whose entry is D is reached (in which case reject) or until index T is reached (in which case accept). These checks are realized in lines 8 to 15 of the algorithm of Figure 3. In order to only spend O ( T ) time, the indices are checked in decreasing order and Quick , a ‘‘short-circuited’’ version of Jump , is built on the fly. After index j is processed in lines 10 to 12, Quick [ j ] either contains the smallest index on the Jump -chain from j whose entry is D , or T if there is no such index. This permits index j to be checked for suffix extension in constant time in lines 13 and 14.

array L [0.. T + D , 0.. T ] vector V [0.. T + D ], Jump [0.. T ], Quick [0.. T ]

  1. procedure GEN( i )
  2. { for a ∈ Σ do
  3. { L [ i ] ← row ( L [ i − 1] , a )
  4. V [ i ] ← a
  5. if L [ i , T ] = D then
  6. V [1.. i ] is in N (^) D

 ( W ).

  1. else if j

min {L [ i , j ] } = D then

  1. Quick [ T ] ← T
  2. for j ← T − 1, T − 2,... 0 do
  3. { Quick [ j ] ← Jump [ j ]
  4. if L [ i , Quick [ j ]] ≠ D then
  5. Quick [ j ] ← Quick [ Quick [ j ]]
  6. if Quick [ j ] = T and L [ i , j ] = D then
  7. V [1.. i ] W j^ is in N (^) D

 ( W ).

  1. }
  2. else
  3. GEN( i + 1)
  4. }
  5. }
  6. Compute Jump [0.. T ].
  7. L [0] (^) ← < 0, 1, 2,. .. T >
  8. if D = 0 then
  9. W is the only member of N (^) D

 ( W ).

  1. else
  2. GEN(1) Figure 3: Refined Neighborhood Generator Algorithm

of symbols after the position, or (4) substitute a different symbol and insert zero or more sym- bols after the position.

Let S ( T , D ) be the number of D -operation edit scripts that adhere to restrictions (1) to (4) above. These scripts do not allow one to insert symbols before the first character of a word (res- triction 0 above). Lemma 1 below presents a recurrence for S and a bound on Z in terms of S.

Lemma 1.

S ( T , D ) =

S ( T − 1, D ) + S ( T − 1, D − 1) + (2| Σ| − 1) j = 1 Σ

D | Σ| j^ −^1 S ( T − 1, D − j )

(2| Σ| − 1)| Σ| D^ −^1

2 | Σ|

1

otherwise

if D > 1 and T = 1

if D = 1 and T = 1

if D = 0

Z ( T , D ) ≤ j = 0 Σ

D | Σ| j^ S ( T , D − j )

Proof. S ( T , 0) = 1 as there is only one empty edit script. In general, note that at a given posi- tion there is 1 script that deletes the symbol there, | Σ| j^ scripts that insert j symbols, and (| Σ| − 1)| Σ| j^ −^1 scripts that substitute a non-identical symbol and then insert j − 1 new symbols. Thus S (1, 1) is 2| Σ| because one may perform one delete (1 script), perform one substitute (| Σ| − 1 scripts), or perform one insert (| Σ| scripts). For S (1, D ) for D > 1, there is only one position at which to perform D operations and deleting is not a possibility. Thus one may per- form D inserts (| Σ| D^ scripts) or a substitute and D − 1 inserts ((| Σ| − 1)| Σ| D^ −^1 scripts). Finally, in the general and recursive case one may either (1) do nothing at the first position and perform D edits at the remaining T − 1 positions ( S ( T − 1, D ) scripts), (2) delete the symbol at the first position and perform D − 1 edits at the remaining T − 1 positions ( S ( T − 1, D − 1) scripts), (3) insert j symbols after the first position for j ∈ [1, D ] and perform D − j edits at the remaining T − 1 positions (| Σ| j^ S ( T − 1, D − j ) scripts), or (4) substitute a non-identical symbol and insert j − 1 symbols at the first position for j ∈ [1, D ] and perform D − j edits at the remaining T − 1 positions ((| Σ| − 1)| Σ| j^ −^1 S ( T − 1, D − j ) scripts).

Certainly Z ( T , D ) is bounded from above by the total number of normalized scripts. The only scripts not counted by S ( T , D ) are those with inserts before the first symbol. The number of normalized scripts where j ∈ [0, D ] symbols are inserted before the first symbol is | Σ| j^ S ( T , D − j ). Thus Z ( T , D ) is bounded by the summation given in the statement of the

Lemma. 

To bound the probability Pr , a recurrence analogous to that for N is developed. In Lemma 2 below, Q ( T , D ) is the sum of the probabilities of matching each word generated by a normal- ized D -operation script that does not insert before the first character. Since different scripts gen- erate the same word, its contribution may be summed several times, and so Q is not necessarily less than 1. It is a bound and not a probability.

Lemma 2.

Q ( T , D ) =

Q ( T − 1, D ) / | Σ| + Q ( T − 1, D − 1) + j = 1 Σ

D Q ( T − 1, D − j )

(2| Σ| − 1) / | Σ|

(3| Σ| − 1) / | Σ|

1 / | Σ| T

otherwise

if D > 1 and T = 1

if D = 1 and T = 1

if D = 0

Pr ( T , D ) ≤ j = 0 Σ

D Q ( T , D − j )

Proof. The argument mimics exactly the proof of Lemma 1 except that now one multiplies by 1 / | Σ| for each character that must be matched. For example, for the case T = 1 and D > 1, each of the | Σ| D^ insertion scripts produce a word that matches with probability | Σ| −^ D^ , and each of the (| Σ| − 1)| Σ| D^ −^1 scripts that substitute and insert produce words that also match with this probability. Thus the sum of the probabilities is | Σ| D^ / | Σ| D^ + (| Σ| − 1)| Σ| D^ −^1 / | Σ| D^ = (2| Σ| − 1) / | Σ|. As the second and final example, consider the recursive formula for Q. If one does nothing at the first position then it will match with probability 1 / | Σ| and the extensions, words obtained by performing D operations on the T − 1 other positions, will match with proba- bility less than Q ( T − 1, D ). This yields the Q ( T − 1, D ) / | Σ| term in the recurrence. If one deletes the first symbol then one must match a word obtained by performing D − 1 operations on the other T − 1 positions and this happens with probability less than Q ( T − 1, D − 1). Inserting j symbols gives | Σ| j^ new symbols which along with the first position match with probability 1 / | Σ| j^ +^1. The extensions match with probability less than Q ( T − 1, D − j ) for a total contribu- tion of Q ( T − 1, D − j ) / | Σ|. Finally, the substitute and j − 1 insert case yields a contribution of Q ( T − 1, D − j )(| Σ| − 1) / | Σ| to the bound. Summing the four cases and doing a bit of algebraic

simplification gives the central recurrence of the Lemma. 

With these recurrences in hand, the bounding expressions for Z and Pr given in Lemma 3 can easily be verified. Slightly tighter bounds for Pr are possible but not necessary since their use does not improve the complexity analysis which is dominated by the expression for Z.

Lemma 3. Let Bnd ( T , D , c ) = ( c − 1

^ c^ +^1 ) T^ c D^ | Σ| D^. For all c > 1,

N ( T , D ) ≤ Bnd ( T , D , c ) Z ( T , D ) ≤ c − 1

^ c Bnd ( T , D , c )

Q ( T , D ) ≤ Bnd ( T , D , c ) / | Σ| T^ Pr ( T , D ) ≤ c − 1

^ c Bnd ( T , D , c ) / | Σ| T

Proof. A simple induction using Lemmas 1 and 2 suffices to verify the correctness of the

bounds. 

In the analyses of the algorithmic components that follow, T will be log (^) | Σ| N or a multiple thereof, where N is the size of the database being searched. Letting ε = D/ T be the permissible mismatch ratio, Lemma 4 below shows that both the Z and Pr quantities are proportional to a power of N that is a concave increasing function of ε.

the record of positions matched in the database ( Pr is smaller). So our first reason to round up, is that we prefer to trade time (which is unbounded) for space (which is bounded). Secondly, the next phase of the algorithm requires O ( D log N ) time per match versus the O ( D ) time spent per neighborhood word. Thus reducing the number of matches is more desirable than reducing the number of words generated. Finally, we have shown in Section 2 that we can conveniently accommodate rounding up for the index structure without increasing the time or space complex- ity of this facet. With this said, we henceforth assume | Σ| is a constant when expressing asymp- totic complexity claims.

5. Finding Hits with the Index

This subsection deals with the details of combining word generation with index lookups and characterizes the complexity and results of this first phase of the total algorithm. Consider the following statement of this first phase problem. One is given a database A = a (^) 1 a (^) 2...^ a (^) N , a word W of length T =

log | Σ| N , and a threshold D. Let Score W ( i ) =

h ≥ i

min { δ( a (^) i a (^) i + 1...^ a (^) h , W ) }. That is, Score (^) W ( i ) is the score of the closest word to W that

begins at position i of the database. Also let Hits (^) W ( D ) = { i : Score (^) W ( i ) ≤ D } , i.e., the set of all positions in the database where a word in the D -neighborhood of W begins. The task is to compute Hits (^) W ( D ).

The solution is to simply run the generator algorithm of Figure 3 and as each word is gen- erated, to look up the indices of the left ends of all occurrences of this word in A with the index. This set of positions, { i : ∃ V ∈ N (^) D

( W ) , V = a (^) i a (^) i + 1...^ a (^) i +| V | − 1 } , is exactly the desired set Hits (^) W ( D ). This follows because if Score (^) W ( i ) ≤ D then there is some word in the D - neighborhood whose leftmost character is at index i , and certainly some prefix of this word is in the condensed D -neighborhood.

Looking up a word V in the neighborhood takes O ( T + DH (^) V ) expected time. Recall that the O ( T ) term is for computing the φ (ρ) code, and that the O ( DH (^) V ) term is for verifying the H (^) V instances found in the relevant index bucket. If realized exactly as described above the time to find all occurrences of all words in the neighborhood would thus be O ( TZ + DH ) expected-time where Z is the size of the condensed neighborhood and H = | Hits (^) W ( D )| is the number of hits. However, the T -term is eliminated by noting that codes can be generated in parallel with the neighborhood words. That is, as each character is added to the string V in Figure 3, the φ-code is easily updated using its defining recurrence, φ( Va ) = φ( V )| Σ| + φ( a ). Moreover, for those words that consist of concatenating the current word with a suffix of W in line 14 of Figure 3, one does not need to explicitly perform the concatenation to do the lookup. If the current word, V , is of length less than T , than consulting a precomputed, (T+1) -element table of the codes of every prefix of W allows the needed code to be delivered in O (1) time.† Whatever suffix of W remains is then used in checking for matches at each position in the appropriate bucket. Thus, as promised earlier, all words, as well as their codes are effectively computed in O ( DZ + T ) worst- case time and the appropriate buckets of the index are checked for hits in O ( DH ) expected time.

† If in line 14 the neighborhood word is V [1.. i ] W j^ and i < T then we need the code for V  W [ j + 1.. j + ( T − i )] and the remainder,

suffix W j^ +^ ( T^ −^ i )^ −^1 , must be checked against bucket positions (or suffix W j^ +^ ( T^ −^ i )^ in the case that the parameter R = 0 for the index structure). But the needed code is simply φ( V )| Σ| T^ −^ i^ + φ( W [ j + 1_._. j + ( T − i )]) and with the table of codes of every prefix of W , the

Lemma 5. Given a precomputed index as described in Section 2, there exists an algorithm to compute Hits (^) W ( D ) in O ( DN pow ( D/T )^ + T ) expected-time and H < 2 N pow ( D/T )^.

Proof. From Lemma 4 it follows that for a database of size N , H is on average Pr ( T , D ) × N <

2 N pow ( D/T )^ / κ^1 −^ pow ( D/T )^ where κ = | Σ| T^ −^ log^ | Σ|^ N^ ∈ [1, | Σ| ]. Thus the result on the size of H follows. Lemma 4 also asserts that Z is O ( N pow ( D/T )^ ). But then the result immediately follows

as the procedure just described takes O ( D ( Z + H ) + T ) expected-time.

As will be subsequently seen, we will also need to solve a "reverse" version of the first phase problem. Specifically, let Score

W ( i ) =^ min h ≤ i{^ δ( a^ h a^ h + 1...^ a^ i ,^ W )^ }^ and let^ Hits

W ( D ) =

{ i : Score

W ( i )^ ≤^ D }.^ These quantities are analogous to their unbarred counterparts above except that they address where matches end as oppose to where they begin. Computing Hits

W ( D ) requires a simple modification of the word generator and index lookup.^ The key observation is that Hits

W ( D ) =^ { i^ :^ ∃^ V^ ∈^ N^ D

( W R^ ) , V R^ = a (^) i −| V | + 1 a (^) i −| V | + 2...^ a (^) i } where W R^ , the reverse of W , is w (^) T w (^) T − 1...^ w (^) 1 .‡ Thus it suffices to generate the condensed neighbor- hood of the reverse of W and then lookup the positions at which the reverse of the neighborhood words match A. The one subtlety is that we have an index for left-to-right matching and we can- not afford the time to reverse a neighborhood word. This is easily solved by computing the "for- ward" codes of the reverse words as they are generated by observing that φ(( Va ) R^ ) = φ( aV ) = φ( a )| Σ||^ V |^ + φ( V ). In addition, the "concatenation" problem for line 14 of Figure 3 can be solved with the O ( T ) table of prefix codes in a fashion similar to that proposed above. Thus we can find the left end of a match to the reverse of a neighborhood word at no additional overhead. For each such location i at which V R^ matches, we need simply record in Hits

W ( D ) the right end of the match, i +| V | − 1.

6. Extending Hits

We now turn to the problem of handling a query W of length P >> T =

log | Σ| N .

Throughout this section we will assume that P/T is a power of 2, i.e., P = 2 K^ T for some K. The case where it is not will be treated at the conclusion of this section. To begin, we review tradi- tional dynamic programming approaches and their graph-theoretic interpretation as finding shor- test paths in an edit graph. With this machinery we prove the decomposition Lemma described in the overview. Finally, we show how to apply this lemma to finding all approximate matches to W in the database A.

As noted at the start of Section 3, the comparison of word W against another word A can be achieved with the computation of a dynamic programming matrix L [0.. N , 0.. P ] where L [ i , j ] = δ( A (^) i , W (^) j ) = min { L [ i , j − 1] + 1, L [ i − 1, j ] + 1, L [ i − 1, j − 1] + ( i f a (^) i = w (^) j then 0 else 1) } for i , j > 0. For the cases where i or j is zero, we have L [ i , 0] = L [0, i ] = i. From a graph-

code for W [ k.. h ] is simply φ( W (^) h ) − φ( W (^) k − 1 )| Σ| h^ −^ k^ +^1.

‡ Care must be taken here to realize that { V R^ : V ∈ N^  D^ ( W R^ ) } is not equal to N^  D^ ( W ). On the other hand, equality does hold in the

case of N (^) D ( W ).

ignore that vertex’s contribution to the 3-way minimum of the recurrence. Let FWk ,^ h^ denote the values of the forward recurrence when evaluated over just this region of the edit graph. Natur- ally FWk ,^ h^ [ i , j ] is the value of a minimum cost path to ( i , j ) over all paths lying between diago- nals k and h. Thus there is a D -path from row 0 to row P between diagonals k and h iff RWk ,^ h^ [ i , 0] ≤ D for some i ∈ [ k , h ], or iff FWk ,^ h^ [ i , P ] ≤ D for some i ∈ [ k + P , h + P ].

W 0 00

W 1 W 11

W 01

V( )ε V 1 V 10 W( )ε

W 10

W

D/4-path

D-path D/2-path

Figure 5: A Sample Edit Graph and Illustration for Lemma 6

With these preliminaries, we now proceed to the central lemma which we lever to efficiently extend matches to subwords of W of length T , to approximate matches to all of W. Consider

dividing the query W in a binary fashion until all pieces are of size T = log | Σ| N  (recall we are

assuming P = 2 K^ T ). To model the various pieces, let W (^) α for α ∈ { 0, 1 } ∗^ be recursively defined by the equations: W (^) ε = W , W (^) α 0 = W (^) α [1..| W (^) α | / 2] (the first half of W (^) α ), and W (^) α 1 = W (^) α [| W (^) α | / 2 + 1_._ .| W (^) α | ] (the second half of W (^) α ). Figure 5 illustrates the decomposition as well as the proof of Lemma 6 below. Note that for a given length k ≤ K , there are 2 k^ distinct labels α of that length and the strings W (^) α are all of length 2 K^ −^ k^ T = P/ 2 k^. Let P (^) α = P/ 2 | α|

denote the length of W α and let D α =  D/ 2 | α|^  be the match stringency to W α required in

Lemma 6 below.

Lemma 6. If W aligns to a string V with not more than D differences, then there exists a word α such that for every prefix β of α, W (^) β aligns to a substring V (^) β of V with not more than D (^) β differences. Moreover, V (^) β a is a prefix or a suffix of V (^) β according to whether a is 0 or 1.

Proof. We show that under the hypothesis it follows that either W (^) 0 or W (^) 1 aligns to a prefix or

suffix, respectively, of V with not more than  D/ 2  differences. Applying this observations

inductively gives the result. If W aligns to V with not more than D differences, than as illustrated in Figure 5 there is a source to sink path of cost D -or-less in the corresponding edit graph. The

path passes through one or more vertices on row P/ 2. Consider the two subpaths consisting of that part of the path from the source to its first vertex in row P/ 2 and the part from its last vertex in row P/ 2 to the sink. By the Pigeon Hole Principle, one of these two subpaths must have cost

not greater than D/ 2 . If its true for the first part, then simply observe that the subpath aligns

W 0 and a prefix of V. If its true for the later subpath, then there is an alignment of cost D/ 2  -

or-less between W 1 and a suffix of V. 

Note that the conclusion of Lemma 6 may be rephrased as: there exists a label α such that for every prefix β of α, W (^) β ε-matches a substring V (^) β of V. This follows simply because for each β

the mismatch ratio of the match between W β and V β is D β / | W β | = D/ 2 | β|^  / ( P/ 2 | β|^ ) ≤

D/ P = ε. Moreover, while the induction of the proof yields the conclusion on progressively smaller subwords, the Lemma gives the strategy for extending approximate matches to progres- sively larger subwords of W. For example, if one finds an ε-match to W (^) 01011 , then one checks for an ε-match to W (^) 0101 and if successful then one checks for an ε-match to W (^) 010 , and so on, until either one fails to match at some level or succeeds in matching all of W = W (^) ε. If this extension strategy is applied to all ε-matches to all subwords W (^) α of length T , then one is guaranteed to detect all ε-matches to W by the Lemma.

The one difficulty in applying the extension strategy is that in a region where there is a partic- ularly stringent match, one can spend an excessive amount of time if one proceeds one match at a time. For example, if F (^) W [ i , P ] = 0, then it is guaranteed that F (^) W [ i ± d , P ] ≤ d because entries along a row or column of the dynamic programming matrix change by − 1, 0, or 1. That is, if there is a 0-match at a particular position, then there are guaranteed to be 2 D additional matches in the immediate neighborhood. Moreover, since W exactly matches this location, then W (^) α matches at corresponding locations for every α. Each of these exact subword matches implies D (^) α matches immediately about them all of which if extended individually would uncover the same matches at the level above. Extending each match of length T would result in the O ( D ) matches to W being discovered O ( D K^ ) times. So clearly, one must accumulate the matches at each level before proceeding to the next. Moreover, one must pursue extensions of adjacent matches simultaneously as otherwise the O ( D ) matches at the upper level will be uncovered O ( D^2 ) times by the level below.

Let F (^) α = { i : F (^) W (^) α [ i , P (^) α ] ≤ D (^) α } , the set of positions at which an ε-match to W (^) α ends.

Similarly, let R (^) α = { i : R (^) W (^) α [ i , 0] ≤ D (^) α } , the set of positions at which an ε-match to W (^) α

begins. Our goal is to compute a representation of either F (^) α or R (^) α for all α in decreasing order of label length. Certainly this suffices because F (^) ε is the set of right ends of ε-matches to W and R (^) ε gives the left ends. Term a list of ordered pairs C = < ( l (^) 1 , u (^) 1 ) , ( l (^) 2 , u (^) 2 ) ,... ( l (^) n , u (^) n ) >

where l (^) k ≤ u (^) k < l (^) k + 1 , a covering list of set X if and only if k = 1

n [ l (^) k , u (^) k ] ⊇ X. For each α of

length less than K our algorithm computes a covering list for F (^) α 0 and one for R (^) α 1. Moreover, these coverings are parsimonious in that if C covers F (^) α ( R (^) α ) then l (^) k , u (^) k ∈ F (^) α ( R (^) α ) and l (^) k + 1 − u (^) k > D (^) α + 1 for all k. Note that these additional conditions uniquely determine the covering list. Furthermore, because values change along a row by − 1, 0, or 1, it follows that for

follows that d = F (^) W (^) α [ i , P (^) α 0 ] cannot be less than F (^) W (^) α [ l , P (^) α 0 ] − ( i − l ) nor less than

F (^) W (^) α [ u , P (^) α 0 ] − ( u − i ). Thus d ≥ D (^) α 0 − min {i − l , u − i}. But then it follows that the second part of the path must lie between diagonals i − P (^) α 0 ± ( D (^) α − d ) ⊆ i − P (^) α 0 ± ( D (^) α − ( D (^) α 0 − min {i − l , u − i} )) = i − P (^) α 0 ± (∆ (^) α + min {i − l , u − i} ) ⊆ [ l − P (^) α 0 − ∆ (^) α , u − P (^) α 0 + ∆ (^) α ].

  1. function UNION( L (^) 1 , L (^) 2 , d , p )
  2. { G (^) ← ∅
  3. u (^) ← − d − 2
  4. while L (^) 1 ≠ ∅ or L (^) 2 ≠ ∅ do
  5. { if L (^) 2 = ∅ or head ( L (^) 1 ). l < head ( L (^) 2 ). l then
  6. ( i , j ) (^) ← pop ( L (^) 1 )
  7. else
  8. ( i , j ) (^) ← pop ( L (^) 2 )
  9. if i − d > u + 1 then
  10. { if u ≥ p and l ≤ N − p then G (^) ← G ( l − p , u − p )
  11. l (^) ← i − d
  12. }
  13. u (^) ← j + d
  14. }
  15. if u ≥ p and l ≤ N − p then G (^) ← G ( l − p , u − p )
  16. return G
  17. } Figure 7: Merging Covering Lists

In the last paragraph we showed that if there is a path between rows 0 and P (^) α of cost D (^) α or less in the edit graph of W (^) α versus A , then it must lie entirely between diagonals l − P (^) α 0 − ∆ (^) α and u − P (^) α 0 + ∆ (^) α for some pair ( l , u ) in the covering list of F (^) α 0 or R (^) α 1. Let L (^) α be the cov- ering list of ∪ { [ l − P (^) α 0 − ∆ (^) α , u − P (^) α 0 + ∆ (^) α ] : ( l , u ) ∈ F (^) α 0 ∪ R (^) α 1 } that is as parsi-

monious is possible, i.e., span ( L (^) α ) = k = 1

n | u (^) k − l (^) k + 1 | is minimal and among those lists whose

span is minimal, L (^) α ’s cardinality, n , is smallest. This list is computable in time linear in the size of the lists F (^) α 0 and R (^) α 1 with the call UNION ( F (^) α 0 , R (^) α 1 , ∆ (^) α , P (^) α 0 ) to the subroutine UNION shown in Figure 7. It consists of simply merging the two ordered lists while "expanding" each pair by ∆ (^) α and "translating" each by − P (^) α 0. Transformed pairs whose intervals overlap are fused into a single pair representing the combined interval.

From the two preceding paragraphs it follows that to compute F (^) α it suffices to compute F (^) W (^) α

only between those diagonals given by pairs of the list L (^) α. Formally, F (^) α =

( l , u ) ∈ L (^) α

∪ { i : FW^ l ,^ (^) α u^ [ i , P (^) α ] ≤ D (^) α }. Replacing F with R gives the analogous result for R (^) α. Let

FSCAN ( L , w , d ) be a procedure that computes Fwl ,^ u^ for each pair ( l , u ) on the list L and exam- ines the last row of this computation to build a covering list of the entries that are less than d. The algorithm is sketched in Figure 8 primarily to confirm the details of the covering list con- struction. The time required by this procedure is O (| w | × span ( L )) and the space required is O ( max{ l − u + 1 : ( l , u ) ∈ L } ). The space requirement could be O ( N ) in the worst-case but in expectation it is O ( D ). By virtue of the preceding remarks it follows that the list returned by the

call FSCAN ( L (^) α , W (^) α , D (^) α ) is a covering list for F (^) α. We assume an analogous procedure RSCAN ( L , w , d ) that computes a covering list for R -sets.

  1. function FSCAN( L , w , d )
  2. { G ← ∅
  3. u ← − d − 2
  4. while L ≠ ∅ do
  5. { ( i , j ) ← pop ( L )
  6. Compute vector Fwi ,^ j^ [?, p =| w | ]
  7. for k ← i + p to min { j + p , N} do
  8. if Fwi ,^ j^ [ k , p ] ≤ d then
  9. { if k − d > u + 1 then
  10. { if u ≥ 0 then G ← G ( l , u )
  11. l ← k
  12. }
  13. u ← k
  14. }
  15. }
  16. if u ≥ 0 then G ← G ( l , u )
  17. return G
  18. } Figure 8: Generating F (^) α ’s covering list from L (^) α when | α| < K

The overall algorithm in terms of the subprocedures — F ( R ) GEN , F ( R ) SCAN , and UNION — is given in Figure 9. The recursive procedure LIST (α) returns a pointer to the covering list L (^) α. When | α| = K − 1, it does so by generating covering lists for F (^) α 0 and R (^) α 1 with the appropriate calls to the neighborhood-based algorithms FGEN and RGEN. It then combines these to form L (^) α with a call to UNION. When | α| < K − 1, the difference is that recursive calls to LIST produce L (^) α 0 and L (^) α 1 which are then used by FSCAN and RSCAN to produce the cover- ing lists for F (^) α 0 and R (^) α 1. At the top level, when L (^) ε is returned it suffices to call RSCAN to

list of pairs G

  1. function LIST(α)
  2. { list of pairs H
  3. if | α| = K − 1 then
  4. { H (^) ← FGEN( W (^) α 0 , D (^) α 0 )
  5. G (^) ← RGEN( W (^) α 1 , D (^) α 1 )
  6. }
  7. else
  8. { H (^) ← FSCAN(LIST(α0), W (^) α 0 , D (^) α 0 )
  9. G (^) ← RSCAN(LIST(α1), W (^) α 1 , D (^) α 1 )
  10. }
  11. return UNION( G , H , ∆ (^) α , P (^) α 0 )
  12. }
  13. G (^) ← LIST(ε)
  14. Report intervals in RSCAN( G , W , D ) Figure 9: The Sublinear Algorithm