Manuscript Offprint
arXiv:2611.05725Faster Approximate Text-to-Pattern Hamming Distances via Near-Optimal Sumset Estimation
Abstract
Text-to-Pattern Hamming Distances is one of the most studied problems in string algorithms: given a text of length and a pattern , the task is to compute the Hamming distance between and every length- substring of . As exact algorithms have been stuck at time for decades, a long line of work has turned to the -approximate version of the problem. Milestones include Karloff's -time algorithm [IPL '93], followed by randomized improvements to by Kopelowitz and Porat [FOCS '15] and recently to by Chan, Jin, Vassilevska W., and Xu [FOCS '23].
In this work, we significantly improve this bound to , using a considerably simpler algorithm. Our algorithm follows the framework of Chan, Jin, Vassilevska W., and Xu, which reduces the problem to a variant of 3SUM that we call Sumset Estimation. We solve Sumset Estimation optimally (up to logarithmic factors) by replacing their matrix multiplication techniques with ideas from sparse recovery. Specifically, we adapt the classic Count Sketch by replacing its random signs with random complex roots of unity—a simple idea that may find further applications for other additive problems.
Finally, we give evidence that our running time might in fact be optimal: we show that the dependence is best possible for a certain natural class of algorithms, including ours and all previous algorithms.
Contents
1 Introduction 1
1.1 Our Improvement ..... 2
2 Preliminaries 3
3 Technical Overview 3
3.1 The Chan-Jin-Vassilevska W.-Xu Algorithm ..... 3
3.2 Our Improvement: A Near-Optimal Algorithm for Sumset Estimation ..... 5
4 Near-Optimal Sumset Estimation 8
4.1 Estimating Heavy Hitters ..... 8
4.1.1 Good Elements and Running Time ..... 9
4.1.2 Correctness Analysis ..... 10
4.1.3 Computing with Complex Numbers ..... 12
4.2 Estimating Sumsets ..... 12
4.3 Estimating Sumsets of Aligned Intervals ..... 14
5 Approximate Text-to-Pattern Hamming Distances 15
6 Matching Lower Bound for a Restricted Class of Algorithms 17
A Reducing Bounded Distance to Short Run-Length Encoding 22
for all shifts .
Exact Algorithms. If the text is much longer than the pattern, a standard trick is to split the text into overlapping pieces of length and to solve each piece independently. For this reason, we assume that throughout and state all bounds in terms of . The first nontrivial algorithm for Text-to-Pattern Hamming Distances is due to Fischer and Paterson [FP74], who computed one convolution per alphabet symbol using the Fast Fourier Transform (FFT), leading to a running time of . This is near-linear for small alphabets, but becomes slow as the alphabet grows. For general alphabets, Abrahamson's classic algorithm [Abr87] runs in time . Remarkably, this algorithm remained unbeaten for more than three decades, until Chan, Jin, Vassilevska Williams, and Xu [CJWX23] recently shaved the remaining logarithmic factor and obtained an -time algorithm. See also [JX24] for a deterministic -time algorithm. A long line of research has also studied the -bounded version of the problem (also known as the -mismatch problem), in which only the Hamming distances up to a given threshold have to be reported [LV86, GG86, LV89, SV96, CH02, ALP04, CFP, GU18, CGK, CKW20, CJWX23], culminating in an -time algorithm [CJWX23]. For the general problem, however, it remains a major challenge to improve the exponent .
Approximation Algorithms. This barrier has motivated a parallel line of research on the -approximate Text-to-Pattern Hamming Distances problem, where the goal is to approximate each Hamming distance up to a multiplicative factor of . This problem was first studied by Karloff [Kar93], who designed a randomized algorithm based on random projections that runs in time . Since then, a major challenge has been to optimize the dependence on ; see Table 1 for an overview. Karloff's dependence remained the state of the art for more than two decades (see also [Ind98] for an alternative, sampling-based algorithm), and it was even believed to be unavoidable: it stems from the variance of random projections, and it matches the lower bound for estimating the Hamming distance in the one-way communication model [Woo04, JKS08]. It thus came as a surprise when Kopelowitz and Porat [KP15] broke this barrier with an -time algorithm based on ideas from sparse recovery. They later obtained a simplified algorithm avoiding the sparse recovery techniques [KP18]. Chan, Golan, Kociumaka, Kopelowitz, and Porat [CGK] showed that the problem can be solved in near-linear time if is not too small (roughly, if ). For smaller , their approach inherently cannot beat .
However, small values of are the most interesting ones. For instance, for the bound coincides with the running time of the exact algorithms, so approximation does not seem to help at all. In a recent breakthrough, Chan, Jin, Vassilevska Williams, and Xu [CJWX23] achieved the first sublinear dependence on , with an algorithm running in time , where is the exponent of matrix multiplication. With the recent bound [Ope26] this becomes and even if , it would be . Their algorithm is built on very different and rather intricate techniques from fine-grained complexity [CWX23], combined with fast matrix multiplication.
Most of these algorithms are randomized, and for a long time the fastest deterministic algorithm remained Karloff's algorithm, which can be derandomized at the cost of one more log-factor in time . Recently, Fischer, Jin, and Xu [FJX25] improved the deterministic dependence to , with a running time
Throughout, suppresses polylogarithmic factors.
The running time stated in [CJWX23] is , which is based on the bound on known at the time.
| Reference | Running Time | Techniques |
|---|---|---|
| Karloff [Kar93] | random projection | |
| Indyk [Ind98] | random sampling | |
| Kopelowitz and Porat [KP15] | random projection + sparse recovery | |
| Kopelowitz and Porat [KP18] | random projection | |
| Chan, Golan, Kociumaka, Kopelowitz, Porat [CGK⁺20] | for | random sampling + rect. matrix mult. |
| Chan, Jin, Vassilevska Williams, Xu [CJWX23] | #3SUM + “Fredman’s trick meets dominance product” | |
| Fischer, Jin, Xu [FJX25] | #3SUM, deterministic approximate | |
| This paper | #3SUM + sparse recovery |
Table 1. Approximation algorithms for Text-to-Pattern Hamming Distances, focusing on the dependence on and ignoring logarithmic factors (assuming that ). Algorithms marked with * are deterministic.
of . In terms of deterministic algorithms, the -dependence hits a natural barrier. For further background on Text-to-Pattern Hamming Distances and related problems (such as approximating other distance measures), we refer to the survey by Uznański [Uzn20].
1.1 Our Improvement
In this paper, we improve the dependence on to :
Theorem 1.1. The -approximate Text-to-Pattern Hamming Distances problem can be solved in time by a randomized algorithm.
This improves upon the previous best -time algorithm [CJWX23], and it even beats the bound that their algorithm would achieve if . For instance, in the interesting regime our algorithm runs in time , whereas the previous best bound was . Another benefit is that our algorithm is considerably simpler: it does not rely on fast matrix multiplication at all, and at its core it uses little more than random sampling and FFT.
Our algorithm builds on the framework of [CJWX23], which reduces approximate Text-to-Pattern Hamming Distances to the following variant of 3SUM that we call Sumset Estimation: Given two sets of integers and a parameter , compute unbiased estimates with variance at most of the number of representations of every sum . Our main technical contribution is a simple, near-optimal algorithm for this problem, running in time (Theorem 3.2); this matches the worst-case output size and is thus optimal up to logarithmic factors. In contrast to [CJWX23], we avoid Fredman’s trick and fast matrix multiplication altogether, and instead rely on techniques from sparse recovery. Specifically, we adapt the classic Count Sketch [CCFC02] by replacing its random signs with random complex roots of unity. This seemingly small change makes the sketch compatible with convolutions, so that it can be computed efficiently by FFT. We believe that this adapted Count Sketch is an interesting tool in itself that may find further applications to additive problems. Along the way, we also simplify parts of the reduction from [CJWX23]. We explain all of these ideas in more detail in our technical overview.
Is This Optimal? In a sense, our algorithm pushes the approach of [CJWX23] to its limit: we leave their reduction to Sumset Estimation essentially unchanged, and our algorithm for Sumset Estimation is optimal up to logarithmic factors, so there is no room for further improvement on this front. But could a different approach lead to an even better dependence on ? In Section 6 we give some evidence that this might be difficult: We consider a natural class of algorithms that independently estimate the number of matches involving each symbol. In particular, our new algorithm as well as the predecessor by Chan, Jin, Vassilevska W., and Xu [CJWX23] are part of this class. We show that, within this class, our algorithm is essentially the fastest possible. The critical regime turns out to be . Here our algorithm runs in time , which matches the exact algorithms, and our hard instance suggests that this is no coincidence. In this regime, beating time seems to require techniques that would also lead to a breakthrough for the exact problem. We stress, however, that this barrier only applies to a restricted class of algorithms, and it is entirely possible that it can be overcome by fundamentally different techniques.
2 Preliminaries
A string of length is a sequence of characters over an alphabet . For indices denote the substring by . A run of a string is a maximal consecutive block of identical characters. The run-length encoding (RLE) of a string is the number of runs in it.
The Hamming distance of two strings is the number of indices at which the strings do not match,
For integers , write and . For two sets of integers , define the sumset and denote the multiplicity of an element by .
For two functions , define the convolution by
Similarly, define the cyclic convolution where the condition is replaced by . It is well-known that both the convolution and the cyclic of two functions can be computed in time by the Fast Fourier Transform.
Define a multiplicative -approximation to a function as a function on the same domain such that for any input in the domain . We define an additive -approximation similarly, with the requirement that .
3 Technical Overview
Before we give the detailed proof, let us start with an informal overview of the ideas behind our algorithm.
3.1 The Chan–Jin–Vassilevska W.–Xu Algorithm
Our algorithm works in the same framework as the previous algorithm due to Chan, Jin, Vassilevska W., and Xu [CJWX23]. To set the stage, we will therefore first describe the key ideas behind that algorithm. It is designed around the following computational problem:
Definition 3.1 (Sumset Estimation). Given sets and a parameter , compute a sparsely represented function such that
In [CJWX23], the authors refer to this problem instead as Approximate Counting All-Numbers 3SUM, but we prefer to stick to the shorter name Sumset Estimation.
(1) for all , and
(2) .
The algorithm can then be seen as an elaborate reduction from Text-to-Pattern Hamming Distances to Sumset Estimation. These two steps can be qualitatively summarized as follows; quantitatively, it is somewhat messy to trace the choice of parameters throughout, so we will omit them.
Step 1: Reduction to Sumset Estimation. The reduction can be split into three substeps. We will mostly leave these steps untouched, but they are helpful to understand how Sumset Estimation is related to pattern matching:
-
From Multiplicative to Additive Approximation: The goal is a multiplicative -approximation for Text-to-Pattern Hamming Distances. Based on previous work by Gawrychowski and Uznański [GU18], this can be reduced to computing an additive ek-approximation for the case when both strings have run-length encodings of size at most k. Additive approximations are more convenient, notably since it is equivalent to compute additive approximations of the number of mismatches and the number of matches.
-
From Hamming Distances to Estimating Convolutions: Next, we reduce to a variant of Sumset Estimation. Specifically, enumerate all characters that appear in text and pattern . Let denote the sets of positions where appears in text and in the reversed pattern. Then the number of matches at shift is exactly
In other words, the quantity we want to estimate can be expressed as the sum of many sumset multiplicities, one for each character . To compute this estimate, apply a simple heavy/light trick. For symbols appearing frequently, compute exactly by one expensive FFT. For infrequent symbols, instead approximate by Sumset Estimation. This is faster, but leads to some estimation error. This basic heavy/light trick dates back to the classic algorithm for (exact) Text-to-Pattern Hamming Distances due to Abrahamson [Abr87]; the difference is that in Abrahamson's algorithm the infrequent symbols are handled by brute force.
- From Run-Length Encoded to Sparse Functions: In substep 1 we have reduced to run-length encoded strings, and so naturally the resulting sets in substep 2 also have small run-length encodings, i.e., they can be described as the union of few intervals. However, they are not necessarily sparse. For this reason, this third reduction step reduces run-length encoded sets to truly sparse sets. It remains to solve multiple instances of the Sumset Estimation problem defined above, one for each infrequent character.
Step 2: Solve Sumset Estimation. In the second step they efficiently solve Sumset Estimation by an algorithm in time for the case when (and when ) [CJWX23, Lemma 3.3]. This is achieved by another heavy/light trick: the small multiplicities can be estimated by naive sampling, and only the large multiplicities require more care. These are estimated in [CJWX23] based on the powerful (yet quantitatively lossy) “Fredman’s trick meets dominance product” technique pioneered in [CWX23] and fast matrix multiplication. Strictly speaking, this heavy/light idea is not implemented directly for Sumset Estimation, but instead by yet another reduction, namely to a variant of the Exact Triangle problem.
In this problem the input consists of an edge-weighted tripartite graph. The goal is to estimate, for each edge, in how many triangles of zero total weight the edge participates. As for the convolution problem, the goal is to achieve an unbiased estimator with small variance.
3.2 Our Improvement: A Near-Optimal Algorithm for Sumset Estimation
In our algorithm we leave Step 1 almost untouched; we only improve it in terms of some technical aspects leading to a cleaner and simpler overall reduction. Our main contribution is a new algorithm for Step 2. We avoid the “Fredman’s trick meets dominance product” technique and fast matrix multiplication altogether. Based on very different techniques from sparse recovery, we obtain a near-optimal algorithm for Sumset Estimation:
Theorem 3.2 (Near-Optimal Sumset Estimation). There is a randomized algorithm that, given and parameters , computes estimates such that:
(1)
(2) , and
(3) the expected number of nonzero estimates is at most .
The algorithm runs in expected time .
To digest this statement, first note that it is crucial that the estimates are returned sparsely, i.e., as a list of the nonzero estimates. If the algorithm were to return an estimate for each , the output size could already reach . But even if the estimates are returned sparsely, the output size is in the worst case. For this reason, Theorem 3.2 is unconditionally optimal, up to log-factors.
For technical reasons, Theorem 3.2 suffers from a small precision error ; i.e., the returned estimates are biased slightly by . For all reasonable purposes, we can set , which leads to negligible error overall, and which does not worsen the running time asymptotically. It will become clear later why our approach naturally leads to some small precision error .
Proof Ideas behind Theorem 3.2. As in [CJWX23], we use the idea that all sumset entries with small multiplicity, namely with , can be estimated with appropriate precision by a naive sampling algorithm. Specifically, sample elements uniformly and independently at random. Then estimate the multiplicity by extrapolating how many samples satisfy . Choosing (matching our time budget) leads to estimates with variance . Whenever , this is sufficiently accurate.
The hard part is to estimate the multiplicities larger than . For this overview let us assume that we know the set ; in the actual algorithm, we will instead use another sampling algorithm to approximate . In the language of sparse recovery, can be viewed as the heavy hitters of the function , and our task of estimating with bounded variance can be viewed as point queries to . This problem is well-studied in the sparse recovery, sketching, and streaming literature: we access the vector via linear queries (i.e., inner products with ), and the goal is to obtain accurate estimates using few queries. It has a prominent solution: the Count Sketch [CCFC02]. Our proof for Theorem 3.2 is essentially a Count Sketch tailored for convolutions, and for this reason we first take a quick excursus into sparse recovery.
To see this, choose any and let . Pick and pick . Both sets have size , and their sumset has size . Moreover, a constant fraction of the sumset entries has multiplicity . Each such entry satisfies , and therefore the Paley–Zygmund inequality implies that
(This inequality applies even though may be negative since .) In particular, we expect to be nonzero for a constant fraction of the sumset entries, and thus the expected output size is .
Excursus: Count Sketch. Fix some function , which can be equivalently viewed as a vector . In a typical sparse recovery setup, we think of as approximately sparse, i.e., as dominated by a few large entries plus noisy small entries. The general goal is to query nonadaptively to subsequently answer queries about , e.g., to approximate the interesting entries of . These nonadaptive queries to are typically linear queries; in such a query we specify a query vector and the output is .
The Count Sketch due to Charikar, Chen, and Farach-Colton [CCFC02] is a core primitive in sparse recovery. It is a randomized algorithm (or data structure if you wish) that, for any parameter , prepares linear queries such that, when provided answers to these linear queries for , we can subsequently estimate arbitrary entries of with good precision. Specifically, we can query the sketch with some and it returns an unbiased estimate of with variance .
The construction behind Count Sketch is simple and elegant. It constructs queries using a hash function , so that every coordinate participates in exactly one of these queries, chosen at random. Furthermore, it chooses a random sign for each coordinate, i.e., . Then, it computes and stores for each the quantity
A point query at can then be answered by returning .
To see why this makes sense, put and observe that the expectation and variance of the resulting estimates can be bounded by
and
Here we have only used the randomness of the random signs, but the randomness of is still unresolved. Thus,
Sumset Estimation via an Adapted Count Sketch. Let us finally return to our setting, where the goal is to estimate the entries of at all query points in . We will apply the Count Sketch with , dictated by our running time budget. There are two issues, both requiring adaptations to the sketch.
The first problem is that the variance bound is not good enough; can be as large as and thus the variance is bounded only by . This is a technical issue with a simple fix: for each query point we will make sure to select a hash function satisfying
a randomly chosen still satisfies this property with constant probability. Then the variance, depending only on the randomness of the signs , can indeed be bounded by
The second issue is much more severe, and its resolution can be seen as the key insight behind our algorithm. Count Sketch requires access to arbitrary linear queries of . However, recall that our goal is to compute to begin with, so we certainly cannot efficiently support arbitrary queries. Our approach is to design appropriate replacements of the queries from above, and the fact that and were both from universal hash families will come in handy.
In particular, we shall make slightly larger, of the order , and choose it to be a random prime number in an interval of size , then set . This ensures, by the Prime Number Theorem, that two distinct elements collide under with probability at most . We can then access all queries of the form
for all , in time . Indeed, let be the functions counting how many elements of fall into the residue classes modulo , i.e., . Compute the cyclic convolution of and via one FFT in time . Then is exactly the -th entry in the cyclic convolution. In other words, we can access the hashed version of the convolution in time by convolving the hashed indicator vectors of and .
Of course, the queries do not account yet for the random signs. And a priori, it seems impossible to incorporate them. A first, wrong attempt could be to adapt g to
for some randomly chosen signs . However, then the convolution is useless, since two terms may contribute to positively and negatively and may therefore cancel. Instead, we need a substitute for random signs that interplays with taking convolutions, i.e., which satisfies and retains the cancellations in the previous calculations. Our solution is to work with random complex roots of unity. The idea of working with roots of unity, or more generally with elements of the complex numbers or of finite fields, has appeared before in [Nak20, BFN21], but for a different purpose, mostly to locate the support of the convolution. Using roots of unity to simulate random signs in a pairwise independent manner is most closely related to ideas from sparse Fourier transforms and norm estimation in streaming algorithms [KNPW11, IKP14].
Recall that is an -th root of unity since it satisfies . Moreover, all integer powers of are -th roots of unity as well. Pick a random , and replace the sign function by defined by . Then the Count Sketch analysis still works out (modulo appropriate technical changes), based on the following basic fact:
Fact 3.3. Let be an integer, let , and let be an integer drawn uniformly at random. Then for all :
Moreover, this alternative choice satisfies and therefore interplays nicely with taking convolutions. Specifically, consider the functions
Their cyclic convolution modulo provides exactly the desired answers to the queries .
All in all, this alternative Count Sketch tailored for convolutions appears to be a powerful tool which we expect to find applications for additive problems beyond just Sumset Estimation. Of course, computing with complex numbers introduces technical issues (like the precision overhead in Theorem 3.2) which we will discuss in the technical part (Section 4.1.3).
4 Near-Optimal Sumset Estimation
4.1 Estimating Heavy Hitters
This section is dedicated to proving the following lemma:
Lemma 4.1 (Estimating Sumset Heavy Hitters). There is a randomized algorithm that, given sets and , and parameters , computes estimates such that, for all ,
(1) , and
(2) .
The algorithm runs in expected time .
Algorithm 1 The sumset heavy hitter estimator (Lemma 4.1).
Input: Sets and
Output: Estimates for all
1: Let , let for some constant , and let
2: repeat
3: Sample a uniformly random prime in the interval
4: Sample uniformly at random
5: Compute the functions defined by
6: Compute the cyclic convolution of and
7: Run Lemma 4.3 to compute a subset of -good elements
8: for each do
9: Set
10: until has been assigned for all
The algorithm behind this lemma is summarized in pseudocode in Algorithm 1. The problem is trivial unless , so we will occasionally assume these bounds. We set ,
for some absolute constant to be determined, and , i.e., a complex -th root of unity. The algorithm runs in rounds, where in each round we will assign some of the unassigned values , but not necessarily all. Once all values are assigned, the algorithm stops. Each round works as follows. We sample a uniformly random prime in the interval . We also sample uniformly at random. Construct the (densely represented) functions defined by
Compute their cyclic convolution :
Now, we want to assign for all ; however, we will do so only for a selected subset of good elements of . This subset is computed by a separate algorithm, stated in Lemma 4.3; why will become clear in the analysis. As is, there remains one issue: the estimates are complex numbers. For now, let us ignore this issue, and further assume that all computations with complex numbers are exact. We will remove this assumption in Section 4.1.3. Note that different elements of can use the same convolution entry . Their estimates may therefore be correlated, which is harmless because Lemma 4.1 only bounds the expectation and variance of each individual estimate.
4.1.1 Good Elements and Running Time
For the analysis, focus on a single round. We will resolve the randomness of and in two stages. Focus on the first stage where we sample . We classify the elements of as follows:
Definition 4.2 (Good Elements). We call -good if
Intuitively, this definition captures exactly the elements of for which the algorithm can produce an accurate estimate, and for that reason, it only assigns for good elements. Of course, this requires computing the set of good elements first:
Lemma 4.3. There is a randomized algorithm to compute a subset containing all -good elements and no elements that are not -good. The algorithm runs in time and succeeds with probability .
Proof. We rely on sampling. Let and sample and uniformly and independently. Write . Mark all for which there is a sample with and . We analyze the probability of marking . Each sample leads to a mark of with probability exactly . If , then the probability of not marking is at most
Conversely, if , then the probability of not marking z is at least
using the estimate for all (a condition that can be assumed here without loss of generality, since Lemma 4.1 is trivial for ).
With this in mind, repeat this process times, and include in all elements from that are marked in the minority of repetitions. Chernoff's bound implies that this includes all -good elements, but no element which fails to be -good, with high probability . The total time is , which is as claimed.
Before we turn to the correctness, let us first analyze the running time of Algorithm 1. To this end, we show that every element in is -good with constant probability:
Lemma 4.4. Each is -good with probability at least (over the random choice of ).
Proof. Observe that
by the Prime Number Theorem and by choosing the constant sufficiently large. By Markov's inequality it follows that with probability at least .
We show that Algorithm 1 runs in expected time as claimed. We first argue that the expected number of iterations is . Indeed, Lemma 4.4 implies that any fixed element is -good with probability at least . Any such element is included into with high probability by Lemma 4.3; once this happens we assign . Thus, after rounds we expect to have assigned all estimates.
We now bound the running time of a single round. Sampling and is negligible (Algorithms 1 to 1). Constructing the functions (Algorithm 1) takes time , and computing their convolution (Algorithm 1) takes time by FFT. Finally, running Lemma 4.3 and assigning the estimates (Algorithms 1 to 1) takes time . Thus, the time per round is . In total, over all rounds, this is as claimed.
4.1.2 Correctness Analysis
Let us finally analyze the correctness. We assume now that the randomness over has already been resolved; condition on the high-probability event that the algorithm from Lemma 4.3 is correct. Fix any and write . We show that, over the remaining randomness of , Properties (1) and (2) from Lemma 4.1 hold. Note that:
Therefore,
using Fact 3.3. For this fact to apply note that and therefore if and only if . Next we focus on the variance. Consider the following calculation, where complex conjugation is denoted by overlines:
Now we use that is -good twice. First, each individual term can be upper bounded by . By a second application, the variance is indeed bounded by
Recall that we have conditioned on the event that Lemma 4.3 succeeds. Let us finally remove that condition. Recall that happens with probability . If fails, then is not necessarily an unbiased estimator. However, even then differs from by at most , and thus the total effect on the expectation is at most . Similarly, if fails then the variance is at most , and thus the effect on the variance is at most
The first term is at most as before, and the second term can also be absorbed by rescaling .
4.1.3 Computing with Complex Numbers
It remains to replace the complex-valued outputs by real-valued outputs, and to remove the assumption that all computations have infinite precision. For the first issue, we can simply discard the imaginary parts for all outputs. Since the expected values are real-valued, this does not affect Property (1), and since the variance can only decrease, this also does not violate Property (2).
For the second issue, we represent complex numbers as pairs , where both components are stored with fixed-point precision in bits. That is, we represent complex numbers with magnitude up to with absolute error at most . This precision error affects the resulting estimates with an absolute error of . This affects the expectation as claimed in the lemma statement; the contribution to the variance can be absorbed by rescaling (using that is smaller and is larger than any absolute constants without loss of generality).
This implementation affects the running time as follows. Each arithmetic operation can be implemented in time . Moreover, it is known that the convolution of two complex-valued functions can be computed without a substantial blow-up in the required precision; specifically, computing the convolution of two length-N sequences with L bits of precision takes time ; see, e.g., [Sch82]. (In fact, we will ultimately set , and for this choice the overhead can be avoided in the word RAM model altogether.) Finally, we need to prepare the root of unity in this representation; this can be done in time e.g., by evaluating the Taylor expansions of the cosine and sine functions to obtain the real and imaginary parts, respectively. This completes the proof of Lemma 4.1.
4.2 Estimating Sumsets
We will now complete the proof of Theorem 3.2, i.e., we will extend the previously established estimator for the heavy hitters to a full estimator for sumset multiplicities .
To estimate the missing light entries, it suffices to use naive sampling. However, we need to do so in two stages: first to classify which elements are heavy hitters and which are light, and second to obtain the light estimates. Both proofs are very similar, though require somewhat incomparable guarantees.
Lemma 4.5 (Heavy/Light Classification). There is a randomized algorithm that, given sets and parameters , computes a partition into light and heavy elements such that and:
(i) for all , , and
(ii) for all , .
The algorithm is correct with probability and runs in time .
Proof. Let and , and draw uniform samples . Write . Let be the set of elements that appear at least times among the samples . The expected number of samples equal to is
Thus, if the expected number of samples is at least , and by Chernoff's bound the number of samples is at least with high probability . Similarly, if , then the expected number of samples is at most , and by Chernoff's bound the number of samples is less than with high probability. Here, in both cases “with high probability” means with probability when choosing the hidden constant in sufficiently large; then a union bound shows that the overall success probability is still at least .
We remark that a derandomization of the previous lemma is known [FJX25], at the cost of an -loss in the running time.
Lemma 4.6 (Light Estimator). There is a randomized algorithm that, given sets and a parameter , computes estimates such that:
(1) for all , and
(2) for all , and
(3) at most estimates are nonzero.
The algorithm runs in expected time .
Proof. Again, draw independent uniform samples and , and let . Let denote the function mapping to , and all other inputs to 0. Compute . Then is an unbiased estimator of because, for any ,
Similarly,
Finally, consider the running time. After preprocessing and in linear time , we can sample the 's and 's in constant time each. Thus, the computation of takes time .
Proof of Theorem 3.2. We start with the algorithm. We may assume (otherwise enumerate ) and replace by . We run the heavy/light decomposition (Lemma 4.5) with some parameter . Let denote the event that the algorithm succeeds; the probability of is at least and we condition on this event for the moment. Denote the resulting sets by and .
We will now separately assign for the values in and . The values for are assigned by one call to Lemma 4.1. For the light ones, we instead run Lemma 4.6 with parameter to compute some estimate and choose for all . For both cases we have . In the heavy case the variance bound is clear, and in the light case it follows from since for all . This proves Properties (1) and (2). For Property (3), we observe that the support of is upper bounded by plus the support of the light estimator; both are at most by Lemmas 4.5 and 4.6.
Let us now remove the condition on the event . Irrespective of , is an unbiased estimator (up to the precision error ), so Property (1) is not affected. Only the variance bound in Property (2) may be affected. For any fixed choice of and , the conditional variance is at most , even if fails. Since all conditional means lie within of , the law of total variance gives
Taking , the extra terms are and can be absorbed into by rescaling , since .
Finally, we analyze the running time. It is dominated by the calls to Lemmas 4.1, 4.5 and 4.6, and the running times of all three lemmas can be bounded by . Lemma 4.5 gives that (unconditionally), therefore, the contribution of to the running time is dominated.
4.3 Estimating Sumsets of Aligned Intervals
For our application to Text-to-Pattern Hamming Distances, it is not sufficient to estimate sumsets of sparse sets A, B. In general, we support estimating sumsets of sets A and B that can be expressed as the union of few intervals (i.e., with small run-length encoding of their indicator strings). Let us call an interval aligned if its starting position is a multiple of its length. The following lemma is sufficient:
Lemma 4.7. There is a randomized algorithm that, given sets that are represented as the union of and aligned intervals of lengths and , respectively, , and parameters , computes estimates such that
(1) for all ,
(2) for all , and
(3) r is a piece-wise linear function represented by an expected number of linear pieces.
The algorithm runs in expected time .
Proof. Let denote the starting positions of the aligned intervals in in the sense that if and only if a -interval starts at position . Similarly, for each , let denote the set of starting positions in that are equal to modulo ; that is, if and only if there is an -interval starting at position . In other words, we have expressed
We apply Theorem 3.2 times, each with the same parameters and , to estimate by . For convenience, assume that out-of-bounds values of are zero. From these estimates we interpolate an estimate of as follows. For each , written as for , let
We claim that this choice indeed satisfies the three properties in the lemma statement. To see this, express as
This condition is equivalent to the two equations and for some carry bit . Hence, and , where . Thus,
It follows that , proving (1) by rescaling . To bound the variance, note that is the sum of at most pairs of terms and , multiplied by some integer at most . Each such term has variance at most . The covariances across different 's are zero (since these are obtained independently), and, based on the fact that , the covariance between any pair and , possibly multiplied with integers up to , is at most . Therefore, the total variance is . Choosing for some sufficiently small hidden constant, the variance becomes , proving (2).
It remains to prove (3), i.e., to bound the number of linear segments required to represent . To this end, note that can be represented by four linear segments: this function has a trapezoid shape, with a first slope-1 segment from 0 to , a second constant segment, and third slope-1 segment from to , and a final constant segment (with value 0). The function can be expressed as the sum of several shifted copies of , where each nonzero entry in leads to at most two copies. Thus, by Theorem 3.2 the expected number of linear segments is bounded by
Finally, consider the running time. The sets and can be constructed in time . Computing the estimates takes time by Theorem 3.2. In total, these calls take time , using that and that . Finally, the function can be assembled in piece-wise linear representation in time proportional to the number of linear pieces, up to logarithmic factors; the expected number of pieces, as argued before, is .
5 Approximate Text-to-Pattern Hamming Distances
In this section we finally prove Theorem 1.1, by giving our -time algorithm for -approximate Text-to-Pattern Hamming Distances.
The first step is to apply the following reduction (which we reprove in Appendix A for convenience):
Theorem 5.1 ([GU18, CJWX23]). Solving the -approximate Text-to-Pattern Hamming Distance problem reduces in time to instances of solving additive -approximate Text-to-Pattern Hamming Distance on two strings of length and run-length encoding at most .
Focus on one instance constructed by the theorem with text and pattern . We assume that and are powers of 2 (with padding if necessary) and that . Instead of approximating the Hamming distances, we approximate the number of matches
for each shift that aligns the pattern with the text. The Hamming distance at shift can then be recovered as minus the number of matches, without worsening the additive approximation error.
We now compute a partition of based on the text . Recall that a dyadic interval is an interval of the form , where and are integers. A basic fact is that every interval in the range can be partitioned into at most consecutive dyadic intervals. We now consider each run in , and partition the corresponding interval into at most dyadic intervals. Overall this results in a partition of into at most dyadic intervals. We similarly partition via the pattern . Now enumerate all pairs of powers of 2 in the ranges and . Let be the string obtained from that retains the characters in the dyadic intervals of length , and let be the string obtained from that retains the characters in the dyadic intervals of length ; replace the deleted characters by some dummy symbol that cannot participate in any matches. To approximate the number of matches between and , it suffices to approximate the number of matches between and over all instances. The total additive error worsens by , which can be absorbed by rescaling .
For the remainder of this section focus only on and . Assume that ; the other case is symmetric. We enumerate all characters s that appear in or . Let
indicate the positions of that character in the text and in the reversed pattern, respectively. By the previous paragraph is the union of aligned intervals of length ; let denote their number. Similarly, is the union of aligned intervals of length . In this notation, the total number of matches at shift can be expressed exactly as
In particular, to estimate the number of matches, it suffices to estimate the sumset multiplicities for all symbols s. We do so in two cases:
- (Heavy) If for some threshold to be chosen, then we compute by one FFT. Naively this takes time . However, we can improve this using that both sets can be seen as unions of intervals of length . We therefore only need to compute the convolution of the sets consisting of the starting points and can interpolate between the aligned points. The running time is .
• (Light) Otherwise we estimate by Lemma 4.7 with parameters and .
Let denote our estimate of and let denote the final estimates. We show that is an additive -approximation of , with probability at least 2/3. First, both cases give unbiased estimators (up to the precision error ), and thus
We pick so that the error term becomes negligible. Now consider the variance. The estimates obtained in the heavy case are deterministic and thus have zero variance. The estimates from the light case contribute:
Thus, Chebyshev's inequality implies that, with probability at least 2/3,
By rescaling by a constant this becomes as claimed. And by repeating this algorithm independently times and selecting the median estimate per , the error probability becomes . This completes the description of the algorithm and the correctness analysis.
It remains to analyze the running time. We can enumerate all symbols in time . In total, there can be at most symbols that fall into the heavy case (each such symbol takes up at least characters in the pattern). Thus, the total time of the heavy case is
By Lemma 4.7 the running time of the light case can be bounded as follows per , ignoring factors for convenience:
Over all symbols , we can bound and , so the total time is
We choose
to balance both contributions; the total time becomes . Finally, we also need to compute the full function by summing over all , but naively spending time per light iteration would be too slow. To this end, we use that each estimated function is represented by an expected number of linear pieces. Using an appropriate range tree data structure, we can thus perform all updates of the form in time proportional to the number of linear pieces, up to log-factors. Hence, this running time can be charged to the running time of the light case as analyzed before. This completes the proof of Theorem 1.1.
6 Matching Lower Bound for a Restricted Class of Algorithms
In this section we show that the running time is best-possible for a certain natural class of algorithms which we call symbolwise algorithms. Before we make this class precise, let us first describe the hard instance. Throughout, focus on the simpler problem to compute an additive en-approximation of all Hamming distances, and focus on the parameter regime . That is, our goal is to compute an additive -approximation of all Hamming distances, or equivalently, of the number of matches per alignment.
Consider the following instance. Let be an alphabet of size . We also include some dummy symbol into that will never participate in matches, and when we delete a character in we mean that it is replaced by . Let . Let be a uniformly random string where we delete each symbol with probability , and let be a uniformly random string. In this instance, each symbol is expected to contribute about 1 match to each shift, and thus the total number of matches per shift is expected to be . The variance is also , and therefore the standard deviation is . In this regime we are forced to consider the contribution of every character. But as each character contributes, say, 0 or 1, we are either forced to spend time per character and per shift, or we risk estimating the contribution which will lead to prohibitively large estimation errors. In the former case we spend time .
Defining the class of algorithms is technically tedious. Informally, we say that an algorithm is symbolwise if it considers the input symbols separately, computes estimates of the number of matches as a sparsely represented function, and aggregates these estimates . Formally:
Definition 6.1 (Symbolwise Algorithms). Let be an algorithm that receives as input sets and reports a sparsely represented function . Then consider the following algorithm for the approximate Text-to-Pattern Hamming Distances problem with input text and input pattern :
-
Initialize as the all-zero function.
-
Enumerate all symbols that appear in text and pattern. For each one, let and , and call algorithm on the sets to compute some sparsely represented function . Then, for each nonzero entry , update .
-
Return as the estimated number of matches (i.e., approximates ).
We call a symbolwise algorithm.
That is, we force the algorithm to consider the symbols separately by making see only one symbol at a time. This class contains the classical exact algorithms by Fischer and Paterson [FP74] and by Abrahamson [Abr87]. Applied to the specific hard instance mentioned above, in the critical regime , the class also contains our algorithm, as well as the predecessor by Chan, Jin, Vassilevska W., and Xu [CJWX23]. Indeed, in both cases the algorithms essentially degenerate to computing one FFT or solving one Sunset Estimation per symbol, without any detours through run-length encoded strings (after all, random strings do not admit run-length compressions). However, the class does not contain the projection-based [Kar93, KP15, KP18] and sampling-based [Ind98, CGK+20] algorithms.
We prove that any symbolwise algorithm cannot beat the barrier.
Lemma 6.2. Any symbolwise algorithm that computes an additive -approximation that is correct with probability at least per alignment requires time in the regime .
The following simple consequence of the Kolmogorov–Rogozin inequality [Rog61] will be helpful:
Lemma 6.3 (Kolmogorov–Rogozin). Let be independent random variables, and let . Then, for any interval of length ,
Here, is an absolute constant.
Proof of Lemma 6.2. Let be a symbolwise algorithm, and let be the corresponding algorithm operating on a single symbol. Let be an alphabet of size , let denote some dummy symbol, and write . Let and , for , be uniformly random strings. Let be the string obtained from by deleting each symbol independently with probability . We consider the execution of on text and pattern , with some parameter for some sufficiently small constant .
A lower bound on the running time of is
since each nonzero entry of a function requires an update that takes time . We will argue that the total number of nonzeroes across must be .
Fix any shift ; it suffices to show that the number of nonzero entries is at least . First, focus on the randomness of and . Let be the set of characters with exactly one match at position , i.e., let
and
Each is placed in with probability : the conditions can be seen as independent Bernoulli variables with probability , and thus behaves like a binomial random variable sampled from . For our choice of parameters, the probability that is . Thus, , and Markov's inequality (applied on ) implies that with probability we have . In this event we call relevant, and we will only focus on the relevant shifts in the following.
Now fix the randomness of and , and only leave the randomness of , i.e., of deleting symbols, unresolved. To match our notation, let
Moreover, write
The sets and are fixed, and is a uniformly random subset. In particular, each character contributes either 0 or 1 match between and , and thus the random variables are independent Bernoulli variables for all .
Now consider the functions returned by the algorithm for the symbols . View as a random variable over the randomness of and over the randomness of the algorithm . Then may be dependent on (in fact, in any reasonable algorithm it should be dependent), but is independent from for any other symbol (since only receives as input and , but not ). Let , and let .
Let us call cheap if . If is cheap, then, intuitively, and cannot be as dependent on each other as they should be. Specifically, for any cheap we must have that
First suppose that at least half the symbols in are cheap; denote these cheap symbols by . Now draw the randomness of for all symbols , and let . By Chernoff's bound, with high probability we have . Now consider the sum
over the remaining randomness of , conditioning only on , each term in the sum behaves like a Bernoulli random variable with parameter . In particular, by the Kolmogorov–Rogozin inequality (Lemma 6.3), there is some interval length such that falls into any fixed length- interval with probability at most . Now recall that the algorithm outputs an estimate which is supposed to satisfy
with probability at least 2/3. However, even when we condition on the outcome of the algorithm, the right-hand side falls into any fixed length- interval with probability at most 1/100. We therefore must have or equivalently . This contradicts our initial choice of when choosing sufficiently small.
We must therefore be in the case that at most half of the symbols in are cheap. In other words, for at least half the symbols , we have . Chernoff's bound implies that in this case the total number of nonzero is with high probability. This proves our initial claim, and completes the proof of Lemma 6.2.
AI Disclosure
No generative AI tools were used to generate the mathematical ideas or writing of this paper. The authors used ChatGPT Astra 6 (OpenAI) and Claude Opus 5.5 (Anthropic) for proofreading and verifying correctness of the subsequent writeup.
References
[Abr87] Karl R. Abrahamson. Generalized string matching. SIAM J. Comput., 16(6):1039–1051, 1987. doi:10.1137/0216067.
[ALP04] Amihood Amir, Moshe Lewenstein, and Ely Porat. Faster algorithms for string matching with k mismatches. J. Algorithms, 50(2):257–275, 2004. doi:10.1016/S0196-6774(03)00097-X.
[BFN21] Karl Bringmann, Nick Fischer, and Vasileios Nakos. Sparse nonnegative convolution is equivalent to dense nonnegative convolution. In Proceedings of the 53rd Annual ACM SIGACT Symposium on Theory of Computing, pages 1711–1724, 2021.
[CCFC02] Moses Charikar, Kevin C. Chen, and Martin Farach-Colton. Finding frequent items in data streams. In Automata, Languages and Programming, 29th International Colloquium, ICALP 2002, pages 693–703. Springer, 2002. doi:10.1007/3-540-45465-9_59.
[CFP+16] Raphaël Clifford, Allyx Fontaine, Ely Porat, Benjamin Sach, and Tatiana Starikovskaya. The k-mismatch problem revisited. In Proceedings of the Twenty-Seventh Annual ACM-SIAM Symposium on Discrete Algorithms, SODA 2016, pages 2039–2052. SIAM, 2016. doi:10.1137/1.9781611974331.ch142.
[CGK+20] Timothy M. Chan, Shay Golan, Tomasz Kociumaka, Tsvi Kopelowitz, and Ely Porat. Approximating text-to-pattern Hamming distances. In Proceedings of the 52nd Annual ACM SIGACT Symposium on Theory of Computing, STOC 2020, pages 643–656. ACM, 2020. doi:10.1145/3357713.3384266.
[CH02] Richard Cole and Ramesh Hariharan. Approximate string matching: A simpler faster algorithm. SIAM J. Comput., 31(6):1761–1782, 2002. doi:10.1137/S0097539700370527.
[CJWX23] 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, pages 2188–2203. IEEE, 2023. doi:10.1109/FOCS57990.2023.00136.
[CKW20] Panagiotis Charalampopoulos, Tomasz Kociumaka, and Philip Wellnitz. Faster approximate pattern matching: A unified approach. In 61st IEEE Annual Symposium on Foundations of Computer Science, FOCS 2020, pages 978–989. IEEE, 2020. doi:10.1109/FOCS46700.2020.00095.
[CWX23] Timothy M. Chan, Virginia Vassilevska Williams, and Yinzhan Xu. Fredman's trick meets dominance product: Fine-grained complexity of unweighted APSP, 3SUM counting, and more. In Proceedings of the 55th Annual ACM Symposium on Theory of Computing, STOC 2023, pages 419–432. ACM, 2023. doi:10.1145/3564246.3585237.
[FJX25] Nick Fischer, Ce Jin, and Yinzhan Xu. New applications of 3SUM-counting in fine-grained complexity and pattern matching. In Proceedings of the 2025 Annual ACM-SIAM Symposium on Discrete Algorithms, SODA 2025, pages 4547–4595. SIAM, 2025. doi:10.1137/1.9781611978322.156.
[FP74] Michael J. Fischer and Michael S. Paterson. String-matching and other products. In Richard M. Karp, editor, Complexity of Computation, SIAM-AMS Proceedings, volume 7, pages 113–125. American Mathematical Society, 1974.
[GG86] Zvi Galil and Raffaele Giancarlo. Improved string matching with k mismatches. SIGACT News, 17(4):52–54, 1986. doi:10.1145/8307.8309.
[GU18] Pawel Gawrychowski and Przemyslaw Uznanski. Towards unified approximate pattern matching for hamming and distance. In 45th International Colloquium on Automata, Languages, and Programming, ICALP 2018, volume 107 of LIPIcs, pages 62:1–62:13. Schloss Dagstuhl - Leibniz-Zentrum für Informatik, 2018. doi:10.4230/LIPIcs.ICALP.2018.62.
[IKP14] Piotr Indyk, Michael Kapralov, and Eric Price. (nearly) sample-optimal sparse fourier transform. In Proceedings of the twenty-fifth annual ACM-SIAM symposium on Discrete algorithms, pages 480–499. SIAM, 2014.
[Ind98] Piotr Indyk. Faster algorithms for string matching problems: Matching the convolution bound. In 39th Annual Symposium on Foundations of Computer Science, FOCS 1998, pages 166–173. IEEE Computer Society, 1998. doi:10.1109/SFCS.1998.743440.
[JKS08] T. S. Jayram, Ravi Kumar, and D. Sivakumar. The one-way communication complexity of Hamming distance. Theory Comput., 4(1):129–135, 2008. doi:10.4086/TOC.2008.V004A006.
[JX24] Ce Jin and Yinzhan Xu. Shaving logs via large sieve inequality: Faster algorithms for sparse convolution and more. In Proceedings of the 56th Annual ACM Symposium on Theory of Computing, STOC 2024, pages 1573–1584. ACM, 2024. doi:10.1145/3618260.3649605.
[Kar93] Howard J. Karloff. Fast algorithms for approximately counting mismatches. Inf. Process. Lett., 48(2):53–60, 1993. doi:10.1016/0020-0190(93)90177-B.
[KNPW11] Daniel M Kane, Jelani Nelson, Ely Porat, and David P Woodruff. Fast moment estimation in data streams in optimal space. In Proceedings of the forty-third annual ACM symposium on Theory of computing, pages 745–754, 2011.
[KP15] Tsvi Kopelowitz and Ely Porat. Breaking the variance: Approximating the Hamming distance in time per alignment. In IEEE 56th Annual Symposium on Foundations of Computer Science, FOCS 2015, pages 601–613. IEEE Computer Society, 2015. doi:10.1109/FOCS.2015.43.
[KP18] Tsvi Kopelowitz and Ely Porat. A simple algorithm for approximating the text-to-pattern Hamming distance. In 1st Symposium on Simplicity in Algorithms, SOSA 2018, volume 61 of OASIcs, pages 10:1–10:5. Schloss Dagstuhl - Leibniz-Zentrum für Informatik, 2018. doi:10.4230/OASICS.SOSA.2018.10.
[LV86] Gad M. Landau and Uzi Vishkin. Efficient string matching with k mismatches. Theor. Comput. Sci., 43:239–249, 1986. doi:10.1016/0304-3975(86)90178-7.
[LV89] Gad M. Landau and Uzi Vishkin. Fast parallel and serial approximate string matching. J. Algorithms, 10(2):157–169, 1989. doi:10.1016/0196-6774(89)90010-2.
[Nak20] Vasileios Nakos. Nearly optimal sparse polynomial multiplication. IEEE Transactions on Information Theory, 66(11):7231–7236, 2020.
[Ope26] OpenAI. An upper bound of 9/4 for the matrix multiplication exponent. OpenAI Math Release preprint, October 2026. URL: https://github.com/openai/math/blob/main/preprints/Matrix-Multiplication-Nine-Fourths-October-2-2026/paper.pdf.
[Rog61] B. A. Rogozin. An estimate for concentration functions. Theory of Probability & Its Applications, 6(1):94–97, 1961. doi:10.1137/1106009.
[Sch82] Arnold Schönhage. Asymptotically fast algorithms for the numerical multiplication and division of polynomials with complex coefficients. In Computer Algebra, EUROCAM 1982, volume 144 of Lecture Notes in Computer Science, pages 3–15. Springer, 1982. doi:10.1007/3-540-11607-9_1.
[SV96] Süleyman Cenk Sahinalp and Uzi Vishkin. Efficient approximate and dynamic matching of patterns using a labeling paradigm (extended abstract). In 37th Annual Symposium on Foundations of Computer Science, FOCS 1996, pages 320–328. IEEE Computer Society, 1996. doi:10.1109/SFCS.1996.548491.
[Uzn20] Przemysław Uznanski. Recent advances in text-to-pattern distance algorithms. In Beyond the Horizon of Computability - 16th Conference on Computability in Europe, CiE 2020, volume 12098 of Lecture Notes in Computer Science, pages 353–365. Springer, 2020. doi:10.1007/978-3-030-51466-2_32.
[Woo04] David P. Woodruff. Optimal space lower bounds for all frequency moments. In Proceedings of the Fifteenth Annual ACM-SIAM Symposium on Discrete Algorithms, SODA 2004, pages 167–175. SIAM, 2004. URL: http://dl.acm.org/citation.cfm?id=982792.982817.
A Reducing Bounded Distance to Short Run-Length Encoding
In this section we prove Theorem 5.1.
Theorem 5.1 ([GU18, CJWX23]). Solving the -approximate Text-to-Pattern Hamming Distance problem reduces in time to instances of solving additive ek-approximate Text-to-Pattern Hamming Distance on two strings of length and run-length encoding at most .
The main component is the following theorem, implicitly proven in [GU18] (Theorem 10, Lemmas 6-9).
Theorem A.1 ([GU18]). Given a pattern of length , text of length and integer , there exists an algorithm running in time that computes strings of length and RLE , a mapping and a constant . For each the algorithm does one of the following:
-
Computes exactly.
-
Discards and determines that .
-
Guarantees that .
We first prove Theorem 5.1 using this result.
Proof of Theorem 5.1. For every power of , define and run the algorithm from Theorem A.1 on . Compute an additive -approximation on the output .
For every index let be the minimal value of for which the iteration of the algorithm with did not discard . Theorem A.1 guarantees that our previous calculations give us an approximation to , denote this approximation by .
If , have constant run-length encodings and so we can compute their exact in constant time, obtaining .
Otherwise, the index was discarded for the previous value of , meaning , so . Therefore, is a multiplicative -approximation to .
Thus, for , computing a multiplicative -approximation to Text-to-Pattern Hamming Distance problem reduces in time to instances of computing an additive approximation to Text-to-Pattern Hamming Distance on strings of length and run-length encoding .
We are left to prove Theorem A.1.
Proof of Theorem A.1. We follow the proof of [GU18], using the kernelization technique of Clifford et al. [CFP 16]. An integer is an -period of a string of length if .
Fact A.2 ([GU18, CFP 16]). If the minimal 2x-period of a pattern is , then the starting positions of any two occurrences with mismatches of the pattern are least distance apart.
The algorithm differentiates between two cases depending on the minimal -period of the pattern . To estimate this period, we use a previous -approximation of Karloff [Kar93], with , to match the pattern against itself in time . The algorithm can be adapted to work for matching suffixes and prefixes instead of the entire string. This allows us to estimate the period and establish one of two cases: (1) every -period of is ; (2) there is an -period of that is .
Case 1: No small 4k-period. We run Karloff's algorithm again with on and identify positions where the 2-approximation reports mismatches, meaning . By Fact A.2, these positions are at least apart so there are at most of them. We can discard all others as they have . For each such , using the technique of Landau and Vishkin [LV86], we count the number of mismatches, either computing exactly or determining that and discarding it in time per position. For all positions this take a total of time.
Case 2: Small 8k-period. Let be some 8k-period of . For a string and denote by the string obtained by taking the characters of at position , . We refer to the concatenations of these strings for all indices as an -encoding' of , . This representation corresponds to writing the characters of in a table of width and reading them out column by column.
Denote by runs(S) the number of runs in and denote by runs. Note that runs. We will use the following two lemmas from [CFP16].
Lemma A.3 ([GU18, CFP 16]). If has an 8k-period for then runs .
Lemma A.4 ([GU18, CFP 16]). Denote by the longest suffix of with and by the longest prefix of with . Let . Then for every such that , is contained in .
Here the -approximation guarantees that the returned estimate satisfies
Thus in this case, our problem is reduced to solving Text-to-Pattern Hamming Distance on , both of whose -encoding has few runs ( ). By using padding of distinct symbols, we can assume and are both divisible by without changing the complexity of our problem. Denote for some .
We now rearrange and P to take advantage of the structure of their -encoding. Define
If we think of the characters of arranged in a table of width , is a string of length including the columns of the table, followed by each column with the first row entry removed and a symbol added at the end. Similarly, is a string of length which includes the columns of the table representation of , with \-signs added after each one. These string preserve the Hamming Distance of , in the following sense.
Lemma A.5 ([GU18]). For any write and . Define , then
Proof. Define the character-inequality function . We have
For any we have . For we have and for we have . For and any j \in [\ell], P^*[i + j \cdot m_1] = \, which creates a mismatch with any character in . Thus,
□
We can now complete the proof. If , by Lemma A.4 we can discard all positions. Otherwise let be the starting position of . Again by Lemma A.4 we can discard any as is not contained in . For the remaining positions define and define as in Lemma A.5. Taking and gives us the desired guarantees - every which is not discarded in this case has,
The strings have length and RLE , as required.