Hamming Distance Oracles
Abstract
In this paper, we present and study the Hamming distance oracle problem. In this problem, the task is to preprocess two strings and of lengths and , respectively, to obtain a data structure that is able to return the Hamming distance between a substring of and a substring of .
For strings over a constant-size alphabet, we show that for every there is a data structure with preprocessing time and query time. We also provide a conditional lower bound, showing that for every there is no combinatorial data structure with query time and preprocessing time unless combinatorial fast matrix multiplication is possible.
For strings over a general alphabet, we present a data structure with pre-processing time and query time for every . Moreover, for every we provide a data structure with a preprocessing time of that returns with high probability a approximation of the Hamming distance of two input substrings. The query time of the approximation data structure is .
Keywords and phrases:
Hamming distance, Fine-grained complexity, Data structure, OracleFunding:
Itai Boneh: partially supported by Israel Science Foundation grant 810/21 and by the Polish National Science Centre grant number 2023/51/B/ST6/01505.Copyright and License:
2012 ACM Subject Classification:
Theory of computation Design and analysis of algorithmsAcknowledgements:
We would like to warmly thank Panagiotis Charalampopoulos for suggesting the approximation version of the problem addressed in this paper.Editors:
Philip Bille and Nicola PrezzaSeries and Publisher:
Leibniz International Proceedings in Informatics, Schloss Dagstuhl – Leibniz-Zentrum für Informatik
1 Introduction
Given two strings of the same length , the Hamming distance is the number of mismatches between and . Formally, . Hamming distance is arguably the most basic and common measure of similarity between strings. The computational task of finding the Hamming distance of two given strings is trivial – it can be done in time and nothing faster is possible.
In recent years, many classical string problems have been considered in the substring queries model. In this model, we are interested in preprocessing a string to obtain a data structure capable of efficiently answering queries regarding its substrings. A few examples of results in the substring queries model include finding the longest increasing subsequence of a substring [21], the longest common substring of two substrings [2], finding the period of a substring [18], and applying pattern matching [17, 19] and approximate pattern matching between substrings [7].
In this paper, we present the natural problem of constructing a Hamming distance oracle.
Problem 1 (Exact Hamming Distance Oracle).
Given two strings of lengths and , respectively, construct a data structure that supports the following query: For a length and two indices and , compute .
We also consider the approximate version of the problem. For an , and , we say that is a -approximation of if .
Problem 2 (Approximate Hamming Distance Oracle).
Given two strings of lengths and , respectively, and , construct a data structure that supports the following query: For a length and two indices and , compute a -approximation of .
Our results.
We begin by considering Problem 1 where the computation is in the word-RAM model. For strings over a constant-size alphabet, we show that for every there exists a data structure with preprocessing time111We use to suppress polylogarithmic factors in the input size. and query time. We also establish a matching conditional lower bound for combinatorial data structures. Our upper bound, however, is non-combinatorial. This is consistent with the situation in the current state-of-the-art bounds for the classical text-to-pattern Hamming distance problem.
Theorem 3 (Informal version of Theorems 7 and 12).
For every there exists a deterministic data structure for the Hamming distance oracle (Problem 1) for strings over a constant size alphabet with construction time and query time . Moreover, there is no combinatorial data structure with query time with a polynomially faster construction.
For strings over a general alphabet, i.e. polynomial integer alphabet, our techniques lead to a data structure with preprocessing time and query time. See Figure 1 for an illustration.
For Problem 2, we show a data structure with construction time and query time (ignoring polynomial factors in ). Formally, we prove the following in Section 4.
Theorem 4.
For every , there is a randomized data structure for Problem 2 with preprocessing time , and query time . The answers of the data structure are correct with high probability.
Related work.
Charalampopoulos et al. [6] considered the problem of constructing an Edit Distance Oracle, namely, preprocessing two input strings and to obtain a data structure that can compute the edit distance between any two substrings of and . They provided an optimal (up to sub-polynomial factors) data structure with preprocessing time and query time, where . It is surprising that the problem of constructing a Hamming distance oracle has not been studied, as Hamming distance is arguably more fundamental than edit distance.
Organization.
In Section 2 we present basic notations and definitions. In Section 3 we prove the stated upper and lower bounds for the (exact) Hamming distance oracles (see Theorem 7 and Theorem 12). Then, in Section 4 we address the approximation version.
2 Preliminaries
For we denote . Also, and .
A string of length over an alphabet is a sequence of characters . For , we call a substring of . If , is a prefix of , and if , is a suffix of . Let and be two strings over an alphabet . is the concatenation of and .
For two strings and of the same length , the Hamming distance [14] of and is defined as .
Text-to-Pattern Hamming distance.
In the Text-to-Pattern Hamming distance problem, we are given a text and a pattern , and we are asked to report for every . Let be the (deterministic) time complexity of computing the Text-to-Pattern Hamming Distance where is the length of the text, is the length of the pattern and both strings are over an alphabet . Notice that for any alphabet we have using FFT (by Fischer and Paterson [10]). For general alphabet we have (by Jin and Xu [16]). We note that if randomization is allowed, one could use the algorithm of Chan et al. [5] that solves the Text-to-Pattern Hamming distance problem in time.
Longest Common Prefix.
The longest common prefix of and , denoted as is the maximal integer such that . Our algorithms make use of the following data structure.
Predecessor, Successor, and Rank.
Let be a sequence. For every , we say that is the rank of in . For a number , the predecessor of in is , and the successor of in is . It is known that an efficient data structure supporting rank, predecessor, and successor queries can be implemented using self-balancing search trees [1, 13].
Fact 6.
Given a sequence , one can construct a data structure supporting the following queries:
-
1.
Given a number , return the predecessor of in .
-
2.
Given a number , return the successor of in .
-
3.
Given , return the rank of in .
The construction time of the data structure is and the query time is .
3 Exact Hamming Distance Oracle
In this section, we present our upper and lower bounds for Problem 1. We also conclude with a brief remark about a bounded variant of Problem 1.
3.1 Data Structure for Problem 1
Here we introduce our data structure for Problem 1 – the Hamming Distance Oracle problem.
Theorem 7.
For every there exists a deterministic data structure for Problem 1 for strings over an alphabet with a preprocessing time and a query time of .
Notice that since for every constant size alphabet we have , the upper bound of Theorem 3 follows directly from Theorem 7. For strings over general alphabet, , so Theorem 7 leads to a data structure with preprocessing time and query time.
We first reduce Problem 1 to the problem of computing the Hamming distance of two suffixes. In order to present our reduction, we slightly abuse the notation and define the Hamming distance between two strings of different lengths as follows: Let and be two strings of lengths and respectively, we define the Hamming distance between and to be the Hamming distance between their prefixes of length . Formally, .
Problem 8 (Suffixes Hamming Distance Oracle).
Given two strings of lengths and , respectively, construct a data structure that supports the following query: For two indices and , compute .
Due to the following fact, given an oracle for Problem 8, one can answer any query of Problem 1 by applying two queries to an oracle for Problem 8.
Fact 9.
For every , and , we have .
Our problem is therefore reduced to proving the following.
Lemma 10.
Let and be two strings over an alphabet , such that , together with . There exists a deterministic data structure for Problem 8 with a preprocessing time of , and a query time of .
Proof.
We first present a simple dynamic programming algorithm, which proves the theorem for . We then show how we can compute only a portion of the dynamic programming table, and then bound the time the data structure needs for answering a query.
Let be a matrix of size such that , i.e. the Hamming distance of the -th suffix of and the -th suffix of . Then, the matrix satisfies the following recursion:
| (1) |
Notice that by Equation 1 one can compute each value in time (assuming a right order of computation). Thus, filling the dynamic programming table takes time in total222Notice that for every alphabet satisfying , it holds that as the input must be read.. Having constructed , we have random access to the answers of all possible queries, and the data structure can answer every query in time, concluding the proof of Lemma 10 for .
We proceed to describe our construction for any .
Preprocessing.
The data structure maintains a small portion of the table : For each , the algorithm computes and stores the -th row, i.e. for each the data structure computes the cell . Notice that (by Fact 9), the value of any cell is the sum of the Hamming distance and (if the indices of the cell are not in the table, we consider the cell value as ). In particular,
Therefore, by computing the rows in decreasing order (and using cells from rows already computed), the data structure is able to compute each row with a single invocation of a text-to-pattern Hamming distance algorithm with text and pattern . In every such invocation, the text’s size is , the pattern size is , and the strings are over alphabet . Therefore the running time per computed row is . Thus, the preprocessing time is as required.
Query.
Let be an input query. Without loss of generality, we focus on the case , since otherwise one can answer a query in time naïvely by comparing up to pairs of characters, even without preprocessing. Let be the minimal integer multiple of larger or equal to and let . The algorithm first computes naïvely by comparing pairs of corresponding characters. Then the algorithm returns . Since is an integer multiple of , we have that is accessible in time after the preprocessing (if is outside the boundaries of , then either or . In either case, the answer to the query can be naively computed in time). Therefore the running time of the query is . The correctness follows immediately from Fact 9 (see Figure 2).
3.2 Lower Bound for Problem 1
In this section we establish the hardness of Problem 1, at least for combinatorial algorithms333The exact meaning of the term “combinatorial” is not well-defined. Nevertheless, techniques based on FFT, and more generally Boolean convolution, which are commonly used in string algorithms, are typically regarded as non-combinatorial.. The lower bound is based on the known conjecture that combinatorial Boolean matrix multiplication cannot be (polynomial) faster than the naïve algorithm.
Conjecture 11 (Combinatorial Matrix Multiplication, see [12, Conjecture 12]).
For any , there is no combinatorial algorithm for multiplying an matrix with an matrix in time 444 [12] stated the running time as . It can be easily shown that our statement is equivalent..
Based on Conjecture 11 we establish the hardness of Problem 1 even for binary alphabet as follows.
Theorem 12 (Lower bound).
Let be a combinatorial oracle for Problem 1 for strings over an alphabet with . Let and be the preprocessing and query time of , respectively. Then there is no such that , unless Conjecture 11 is false.
Proof.
Our reduction is based on an idea attributed to Ely Porat and Piotr Indyk [8] that was later generalized by Gawrychowski and Uznanski [12]. Assume by contradiction that there exists some such that . Let and note that . Let and be two Boolean matrices of sizes and , respectively. The idea is to create a string representing the rows of and a string representing the columns of . We transform each row of and each column of such that the Hamming distance between the row’s string and the column’s string indicates the Boolean product of the corresponding row and column. We first show a construction using ternary alphabet, and then explain how one can convert it into a binary alphabet.
Encoding.
We define encoding of values into characters, which is as follows:
-
each is encoded by the character .
-
each from is encoded by the character .
-
each from is encoded by the character .
For each the algorithm encodes the th row of as , and for each the algorithm encodes the th column of as . Then is the concatenation of ’s rows (i.e. ), and is the concatenation of ’s columns (). The resulted strings and have length of and (respectively), and then the algorithm creates the Hamming Distance Oracle data structure of and . We prove the following connection between Boolean matrix product and the Hamming distance of row strings and column strings.
Claim 13.
.
Proof.
if and only if there exists some such that . That means that both and were encoded by the character , and . This implies that for and there is a match in at least one index, and therefore .
For the other direction, if , then for some there is a match in . Since does not occur in and does not occur in , it must be that . Therefore, and thus .
To prove the hardness for binary alphabet one can find a binary encoding for each symbol in that preserves the mismatches: for each it holds that . Then, the reduction construction is modified to check if the distance between and is strictly less than . An example for such encoding is .
Due to Claim 13 and the discussion above, the algorithm would query the data structure for each entry of if and fill in the matrix accordingly.
The correctness comes directly from Claim 13. Thus, using the oracle , one can compute the Boolean matrix product in time.
Recall that and . Thus, we get that
Moreover,
Thus, the time for computing the product using the oracle is , which contradicts Conjecture 11 that suggests that no algorithm can compute in time.
3.3 Remark: -bounded Oracle
One can consider the -bounded version of Problem 1 (for some threshold number ), where one is interested in either reporting the Hamming distance of two input substrings, or reporting that it is larger than the threshold . We refer to this relaxed variant of a Hamming distance Oracle as a -bounded Hamming distance oracle. The following lemma uses the method sometimes called “the Kangaroo method” [3] to construct such an oracle using near-linear time and achieves query time.
Lemma 14.
Given two strings and over an alphabet , such that , and . There exists a deterministic data structure that after preprocessing time answers -bounded Hamming Oracle queries of any two substrings in time.
Proof.
As a preprocessing, the data structure only builds the data structure of Lemma 5 on which takes time. On a query , the algorithm queries the data structure to find the first mismatch between and . If the mismatch is after and , the algorithm reports that the Hamming distance is . Otherwise, the algorithm found the first mismatch such that . The algorithm computes recursively and returns the reported result with the addition of (for the mismatch ). Finally, if the depth of the recursion becomes more than , the algorithm reports that there are more than mismatches, meaning and halts. Since every level of the recursion performs a single query, the running time of the algorithm is per level of the recursion, which is in total. We remark that the actual implementation of the query algorithm can be done iteratively, rather than recursively, to optimize space usage and time overhead.
If one is interested in a -bounded Hamming distance oracle with query time, one can simply use the data structure of Theorem 7, obtaining a similar preprocessing-query time tradeoff. One can observe that the lower bound of Theorem 12 holds for -bounded Hamming oracles in the regime in which the query time is (i.e., the queries used in the lower bound construction are between pairs of substrings with Hamming distance at most between them). Therefore, in the regime in which the query time is and the alphabet is constant, the trade-off of Theorem 7 cannot be beaten by a combinatorial algorithm, even for a -bounded oracle.
4 Approximate Hamming Distance Oracle
In this section, we prove Theorem 4, repeated below for easy reference. See 4 We follow the ideas of Chan et al. [4] to obtain an oracle for -approximated Hamming Distance. The algorithm of Chan et al. [4] solves the problem of approximating text-to-pattern Hamming distances. Using their techniques, with even simpler details, one can obtain the desired oracle. We provide here all the details, requiring repeating many notations and claims from [4].
We first state the definition of -estimate. For some integer , we say that is an -estimate of if the following holds:
-
if , then ;
-
if , then ;
-
if , then .
We further follow [4] and introduce an integer parameter controlling the probability that the algorithm returns correct answers. For a query regarding the Hamming distance of and , define so that . Our algorithm estimates the size of for an appropriately chosen integer . By the following lemma, if is a prime number picked uniformly at random from a certain range, then holds with probability . Thus, a good estimate of is also a good estimate for . The following lemma was proved in [4].
Lemma 15 ([4, Lemma 3.1]).
Let be a random prime in , where . For every set of size , the probability that is .
Let be an integer. We use the notion of offset strings. Let denote a concatenation. For a string and an integer , we define the th offset string of as
Notice that
Picking random offsets.
Our algorithm picks a random subset of elements , with sampling rate . Let be the event that there exists some such that . The following lemma was proved in [4].
Lemma 16 ([4, Lemma 3.2]).
.
Our algorithm tests whether happens. This is equivalent to testing if
Finally, in order to extract an estimate of , the algorithm repeats the process with independent choices of . The algorithm computes which is the overall number of times that the event took place throughout the executions. Finally, the algorithm sets (so that ). The following pseudo-code summarizes the sampling algorithm, whose correctness follows from Lemmas 15 and 16, and a standard use of Chernoff bounds. We emphasize that Line 7 only describes what mathematical objects we compute to approximate the Hamming distance. We later describe how to efficiently preprocess and to obtain this approximation in time on query time.
The following lemma was proved in [4] (with some more complicated details).
Implementation details
Following the discussion above, our goal is to run Line 7 in time given a query. Notice that the computation of boils down to testing if exactly times. We show how to efficiently preprocess and to answer this query in time.
Lemma 18.
Given two strings and , an integer , and a set , there is an algorithm that constructs a (deterministic) data structure for supporting the following query: Given , report if with and . The preprocessing time is and the query time is .
Proof.
For every , let (in increasing order) and let (in increasing order). Let and . Notice that for every there exist , and such that . Specifically, this equality holds for such that , is the rank of the successor of in and is the rank of the predecessor of in . Similarly, for every there exist , and such that . Specifically, this equality holds for such that , is the rank of the successor of in and is the rank of the predecessor of in .
As a preprocessing step, the algorithm constructs for every the sequences and , and constructs predecessor/successor data structures for and for . The algorithm also constructs strings and , and constructs an data structure over . Notice that for every , it holds that and . Therefore, . The construction time of all above data structures is therefore .
When a query is given, the algorithm finds and such that and and such that (where finding and is done using predecessor and successor queries on and ). Since the positions of and of within are known, the indices can be easily shifted to the corresponding occurrences of and of in . As we have found a representation of and of as substrings of , we can use the data structure of to check if in constant time. The time complexity of the query is dominated by the invocation of the predecessor/successor data structures to find , and . The running time is therefore .
We now discuss how to use Lemmas 17 and 18, to preprocess , , and and support the following query: Given return an -estimate of . Let , the algorithm picks a random prime . For , the data structure generates independent samples with sampling rate from . The algorithm then applies Lemma 18 on , , and for every . The preprocessing takes expected time (since and ). At query time, the algorithm uses the preprocessing of Lemma 18 to check if for every and compute and accordingly as in Line 7 of Line 7. It is immediate from Lemma 17 that the output is indeed an -estimate of with probability . The running time of the query is . Choosing to be a large enough constant implies a small constant error probability. In order to achieve -estimate of with high probability, it suffices to construct instances of the above data structure and return the median of the answers while processing a query.
To obtain Theorem 4, we construct the above data structure for every value of which is a power of and is at most . While processing a query, the algorithm obtains an -estimate for each . Let be the estimate computed for . If one of these estimates satisfies , the algorithm reports as the approximation of . Since with high probability every is an -estimate, the reported value is indeed . Moreover, for the (correct) value of such that , with high probability . Thus, the algorithm is correct with high probability. The construction takes555We note that using a slightly more complicated construction, following Chan et al. [4], one can speedup the construction time to be . However, we preferred to put a simpler version here for the reader’s ease. time and the query time is .
References
- [1] G. M. Adelson-Velsky and E. M. Landis. An algorithm for the organization of information. Doklady Akademii Nauk SSSR, 146:263–266, 1962.
- [2] Amihood Amir, Panagiotis Charalampopoulos, Solon P Pissis, and Jakub Radoszewski. Dynamic and internal longest common substring. Algorithmica, 82(12):3707–3743, 2020. doi:10.1007/S00453-020-00744-0.
- [3] Amihood Amir, Moshe Lewenstein, and Sharma V. Thankachan. Range LCP queries revisited. In Costas S. Iliopoulos, Simon J. Puglisi, and Emine Yilmaz, editors, String Processing and Information Retrieval - 22nd International Symposium, SPIRE 2015, London, UK, September 1-4, 2015, Proceedings, volume 9309 of Lecture Notes in Computer Science, pages 350–361. Springer, 2015. doi:10.1007/978-3-319-23826-5_33.
- [4] Timothy M. Chan, Shay Golan, Tomasz Kociumaka, Tsvi Kopelowitz, and Ely Porat. Approximating text-to-pattern hamming distances. In Konstantin Makarychev, Yury Makarychev, Madhur Tulsiani, Gautam Kamath, and Julia Chuzhoy, editors, Proceedings of the 52nd Annual ACM SIGACT Symposium on Theory of Computing, STOC 2020, Chicago, IL, USA, June 22-26, 2020, pages 643–656. ACM, 2020. doi:10.1145/3357713.3384266.
- [5] Timothy M. Chan, Ce Jin, Virginia Vassilevska Williams, and Yinzhan Xu. Faster algorithms for text-to-pattern hamming distances. In 64th IEEE Annual Symposium on Foundations of Computer Science, FOCS 2023, Santa Cruz, CA, USA, November 6-9, 2023, pages 2188–2203. IEEE, 2023. doi:10.1109/FOCS57990.2023.00136.
- [6] Panagiotis Charalampopoulos, Pawel Gawrychowski, Shay Mozes, and Oren Weimann. An almost optimal edit distance oracle. In Nikhil Bansal, Emanuela Merelli, and James Worrell, editors, 48th International Colloquium on Automata, Languages, and Programming, ICALP 2021, July 12-16, 2021, Glasgow, Scotland (Virtual Conference), volume 198 of LIPIcs, pages 48:1–48:20. Schloss Dagstuhl – Leibniz-Zentrum für Informatik, 2021. doi:10.4230/LIPIcs.ICALP.2021.48.
- [7] Panagiotis Charalampopoulos, Tomasz Kociumaka, and Philip Wellnitz. Faster approximate pattern matching: A unified approach. In 2020 IEEE 61st Annual Symposium on Foundations of Computer Science (FOCS), pages 978–989. IEEE, 2020. doi:10.1109/FOCS46700.2020.00095.
- [8] Raphaël Clifford. Matrix multiplication and pattern matching under Hamming norm. URL: https://web.archive.org/web/20160818144748/http://www.cs.bris.ac.uk/Research/Algorithms/events/BAD09/BAD09/Talks/BAD09-Hammingnotes.pdf, 2009.
- [9] Martin Farach. Optimal suffix tree construction with large alphabets. In 38th Annual Symposium on Foundations of Computer Science, FOCS 1997, Miami Beach, Florida, USA, October 19-22, 1997, pages 137–143. IEEE Computer Society, 1997. doi:10.1109/SFCS.1997.646102.
- [10] Michael J Fischer and Michael S Paterson. String-matching and other products. Technical report, Massachusetts Institute of Technology, 1974.
- [11] Zvi Galil and Raffaele Giancarlo. Data structures and algorithms for approximate string matching. Journal of Complexity, 4(1):33–72, 1988. doi:10.1016/0885-064X(88)90008-8.
- [12] Pawel Gawrychowski and Przemyslaw Uznanski. Towards unified approximate pattern matching for hamming and l_1 distance. In Ioannis Chatzigiannakis, Christos Kaklamanis, Dániel Marx, and Donald Sannella, editors, 45th International Colloquium on Automata, Languages, and Programming, ICALP 2018, July 9-13, 2018, Prague, Czech Republic, volume 107 of LIPIcs, pages 62:1–62:13. Schloss Dagstuhl – Leibniz-Zentrum für Informatik, 2018. doi:10.4230/LIPIcs.ICALP.2018.62.
- [13] L. J. Guibas and R. Sedgewick. A dichromatic framework for balanced trees. Information and Control, 15(1):1–29, 1978.
- [14] Richard W Hamming. Error detecting and error correcting codes. The Bell system technical journal, 29(2):147–160, 1950.
- [15] Dov Harel and Robert Endre Tarjan. Fast algorithms for finding nearest common ancestors. SIAM J. Comput., 13(2):338–355, 1984. doi:10.1137/0213024.
- [16] Ce Jin and Yinzhan Xu. Shaving logs via large sieve inequality: Faster algorithms for sparse convolution and more. In Bojan Mohar, Igor Shinkar, and Ryan O’Donnell, editors, Proceedings of the 56th Annual ACM Symposium on Theory of Computing, STOC 2024, Vancouver, BC, Canada, June 24-28, 2024, pages 1573–1584. ACM, 2024. doi:10.1145/3618260.3649605.
- [17] Orgad Keller, Tsvi Kopelowitz, Shir Landau Feibish, and Moshe Lewenstein. Generalized substring compression. Theoretical Computer Science, 525:42–54, 2014. doi:10.1016/J.TCS.2013.10.010.
- [18] Tomasz Kociumaka, Jakub Radoszewski, Wojciech Rytter, and Tomasz Waleń. Efficient data structures for the factor periodicity problem. In String Processing and Information Retrieval: 19th International Symposium, SPIRE 2012, Cartagena de Indias, Colombia, October 21-25, 2012. Proceedings 19, pages 284–294. Springer, 2012. doi:10.1007/978-3-642-34109-0_30.
- [19] Tomasz Kociumaka, Jakub Radoszewski, Wojciech Rytter, and Tomasz Walen. Internal pattern matching queries in a text and applications. SIAM J. Comput., 53(5):1524–1577, 2024. doi:10.1137/23M1567618.
- [20] Gad M. Landau and Uzi Vishkin. Fast string matching with k differences. Journal of Computer and System Sciences, 37(1):63–78, 1988. doi:10.1016/0022-0000(88)90045-1.
- [21] Alexandre Tiskin. Semi-local string comparison: Algorithmic techniques and applications. Math. Comput. Sci., 1(4):571–603, 2008. doi:10.1007/S11786-007-0033-3.
