Abstract 1 Introduction 2 Preliminaries 3 Cartesian Periodicity 4 Approximate CT-Matching with Substitutions 5 Conclusions and Open Problems References

Approximate Cartesian Tree Matching
with Substitutions

Panagiotis Charalampopoulos ORCID King’s College London, UK Jonas Ellert ORCID DIENS, École normale supérieure de Paris, PSL Research University, France Manal Mohamed ORCID King’s College London, UK
Abstract

The Cartesian tree of a sequence captures the relative order of the sequence’s elements. In recent years, Cartesian tree matching has attracted considerable attention, particularly due to its applications in time series analysis. Consider a text T of length n and a pattern P of length m. In the exact Cartesian tree matching problem, the task is to find all length-m fragments of T whose Cartesian tree coincides with the Cartesian tree CT(P) of the pattern. Although the exact version of the problem can be solved in linear time [Park et al., TCS 2020], it remains rather restrictive; for example, it is not robust to outliers in the pattern.

To overcome this limitation, we consider the approximate setting, where the goal is to identify all fragments of T that are close to some string whose Cartesian tree matches CT(P). In this work, we quantify closeness via the widely used Hamming distance metric. For a given integer parameter k>0, we present an algorithm that computes all fragments of T that are at Hamming distance at most k from a string whose Cartesian tree matches CT(P). Our algorithm runs in time 𝒪(nmk2.5) for km1/5 and in time 𝒪(nk5) for km1/5, thereby improving upon the state-of-the-art 𝒪(nmk)-time algorithm of Kim and Han [TCS 2025] in the regime k=o(m1/4).

On the way to our solution, we develop a toolbox of independent interest. First, we introduce a new notion of periodicity in Cartesian trees. Then, we lift multiple well-known combinatorial and algorithmic results for string matching and periodicity in strings to Cartesian tree matching and periodicity in Cartesian trees.

Keywords and phrases:
Cartesian tree, Hamming distance, approximate pattern matching
Funding:
Jonas Ellert: Partially funded by grant ANR20-CE48-0001 from the French National Research Agency.
Copyright and License:
[Uncaptioned image] © Panagiotis Charalampopoulos, Jonas Ellert, and Manal Mohamed; licensed under Creative Commons License CC-BY 4.0
2012 ACM Subject Classification:
Theory of computation Pattern matching
Related Version:
Full Version: https://arxiv.org/abs/2602.08570
Acknowledgements:
We thank the anonymous reviewers of STACS 2026 for their helpful feedback.
Editors:
Meena Mahajan, Florin Manea, Annabelle McIver, and Nguyễn Kim Thắng

1 Introduction

Pattern matching is a central topic in theoretical computer science and a ubiquitous task in practical applications. In several real-world scenarios, such as stock price analysis and music analysis, one may wish to match a pattern with respect to the relative order between its sequential data points rather than their exact values. For instance, consider the challenge of matching the performance of a stock in the past quarter to its historical performance in order to predict its future behaviour. In this task, we are not concerned with the exact stock price but rather with its “ups and downs”. Several notions of matching have been devised for capturing such scenarios, including Cartesian tree matching [1, 20, 26, 28, 29, 31] and order-preserving pattern matching [5, 7, 8, 9, 13, 15, 17, 22, 25, 30]. Here, we focus on the Cartesian tree matching problem, which was introduced by Park et al. [29].

A Cartesian tree CT(S) of a string S is a binary tree defined recursively as follows: the root of the tree corresponds to the index i of the minimum element in the sequence (under a fixed tie-breaking strategy); the left subtree of the root corresponds to the Cartesian tree of S[1..i1], and the right subtree of the root corresponds to the Cartesian tree of S[i+1..|S|]. In what follows, we assume that ties are always resolved in favour of the leftmost elements. The Cartesian tree of a string S can be built in linear time [2].

We say that a string U CT-matches a string V if and only if CT(U)=CT(V). This notion of matching is well-behaved: it is a prime example of substring consistent equivalence relations [23] since, if U and V CT-match, then, for any 1ij|U|, U[i..j] and V[i..j] CT-match as well [29].

In the Cartesian tree matching (CT-matching) problem, we are given a text T of length n and a pattern P of length m, and the goal is to compute all m-length fragments of T that CT-match P. Park et al. [29] showed that this problem admits a linear-time solution. An alternative linear-time algorithm, as well as practical solutions, were later presented in [31]. Related problems such as dictionary CT-matching [29, 31] and indexing for CT-matching [20, 26, 28] have also been studied.

Approximate Cartesian tree matching.

Similarly to the case of standard string matching, requiring exact CT-matches can be quite restrictive. For instance, a single outlier value in the pattern (arising, for example, from an extreme but short-lived event or from noise in the data) may cause all relevant occurrences in the text to be missed. To address this, one can instead seek approximate CT-matches of P in T, that is, fragments of T that are close to a string X such that CT(X)=CT(P). Here, closeness may be measured in terms of some distance measure such as the Hamming distance or the edit distance. We consider the low distance regime, where an integer threshold parameter k>0 is provided. Then, we have to report fragments of T at distance at most k from a string X with CT(X)=CT(P).

Auvray et al. [1] recently presented an 𝒪(nm)-time algorithm for the case of one difference (such as a swap or a substitution). Kim and Han [21] studied the problem of computing the edit and Hamming distances of two strings under CT-matching. They presented a dynamic-programming-based solution and, as corollaries, obtained an 𝒪(n3mk)-time algorithm for approximate CT-matching under the edit distance and an 𝒪(nmk)-time algorithm for approximate CT-matching under the Hamming distance. In this work, we focus on approximate CT-matching under the Hamming distance.

Our contributions.

For equal-length strings X and Y, let CHd(XY) denote the minimum number of substitutions needed to transform X into a string X such that CT(X)=CT(Y). We further define CHdk(XY)=min{k+1,CHd(XY)}. We consider the following problem.

Approximate CT-Matching with Substitutions Input: A text T of length n, a pattern P of length m, and an integer threshold k>0. Output: CHdk(T[i..i+m)P) for all i[1,nm+1].

The state of the art solution of Kim and Han [21] computes CHdk(T[i..i+m)P) for each i[1,nm+1] separately in 𝒪(mk) time, resulting in 𝒪(nmk) overall time. In the spirit of a line of works in approximate string matching (see, e.g., [4, 6]), we show that this is not necessary by transferring the “few matches or almost periodicity” paradigm to approximate CT-matching. We obtain the following result.

Theorem 1.

The Approximate CT-Matching with Substitutions problem can be solved in 𝒪(nmk2.5) time for k[1,m1/5] and in 𝒪(nk5) time for any k[m1/5,m].

Hence, we improve upon the state of the art by polynomial factors when k=𝒪(m1/4ϵ) for any constant ϵ>0. An illustration of the time complexities of our algorithm and the algorithm of Kim and Han [21] for the important case when n=Θ(m) is given in Figure 1. Along the way to proving Theorem 1, we develop a toolbox that we expect to find further applications in the study of Cartesian trees.

Figure 1: The running time t(n,k) of algorithms for Approximate CT-Matching with Substitutions as a function of k for the special case when m=Θ(n), shown on a doubly logarithmic scale.

Technical overview.

It is a folklore fact that a pattern P of length m is either periodic or it has at most one exact occurrence in a text T of length n3m/2 [3]. In approximate string matching, recent algorithmic breakthroughs [4, 6] were obtained via analogous combinatorial results: either P has few approximate occurrences in T, or P is almost periodic.

In the CT-matching model, it is not even clear what the right formalisation of periodicity is. Indeed, several notions of periodicity have been suggested and studied thus far [23, 29]. Here, we introduce a new notion of periodicity, namely CT-block-periodicity, that provides strong locality guarantees. We then exploit these guarantees to show that we either have few approximate CT-matches or the pattern is almost CT-block-periodic. Dealing with the almost CT-block-periodic case is the main technical challenge we overcome. The workhorse of our approach for this case is a combinatorial result (see Lemmas 31 and 34 for precise statements) that allows us to compute CHdk(T[i..i+m)P) very efficiently for almost all values of i when P is almost CT-block-periodic. Essentially, we prove (under some extra assumptions) that, for equal-length strings X=X1QrX2 and Y=Y1QrY2 with |X1|=|Y1|, the value of CHdk(XY) is the same for all choices of r2k+1.111We use Qr for simplicity in this overview, noting that standard string periodicity implies CT-block-periodicity. Lemmas 31 and 34 are more general. This allows us to trim aligned pairs of long CT-block-periodic fragments in T[i..i+m) and P, thus obtaining short strings F and P such that CHdk(T[i..i+m)P)=CHdk(FP), and compute the latter value in 𝒪(|F|k) time. In summary, in the case when the number of (candidate) approximate CT-matches may be large, the periodic structure allows us to verify almost all of them efficiently.

Other related work.

Cartesian trees have received significant attention in part due to their relation to the range minimum query problem [2, 10, 12]. Other problems that have been studied in the Cartesian tree matching model include computing the longest common subsequence [32], performing subsequence matching [27], computing palindromes [24], and matching indeterminate strings [14]. Other works on strings under substring consistent equivalence relations include [16, 18, 19].

2 Preliminaries

For integers i,j, we write [i,j]=[i,j+1)=(i1,j]=(i1,j+1) to denote {hihj}. For a set Z and an integer y, we define Zy={zy:zZ}.

A string X of length n=|X| is a finite sequence of n characters over a finite alphabet Σ. For i,j[1,n], the i-th character of X is denoted by X[i], and we use either of X[i..j], X[i..j+1), X(i1..j], and X(i1..j+1) to denote the substring X[i]X[i+1]X[j] of X. If i>j, then X[i..j] is the empty string. We say that a string Y has an occurrence at position i of X if i+|Y||X|+1 and X[i..i+|Y|)=Y. We may refer to a substring X[i..j] as a fragment if we want to emphasize that we mean the specific occurrence of X[i..j] at position i. Two fragments are disjoint if they do not share any positions.

An integer p>0 is a period of X if X[i]=X[i+p] for all i[1,|X|p]. The smallest period of X is referred to as the period of X and is denoted by per(X). A run in X is a fragment Y=X[i..j] that satisfies p:=per(Y)|Y|/2 and is inclusion-maximal; that is, X[i1]X[i1+p] (or i=1) and X[j+1]X[j+1p] (or j=|X|).

Lemma 2 (Periodicity Lemma (weak version) [11]).

If a string S has periods p and q such that p+q|S|, then gcd(p,q) is also a period of S.

Throughout the paper, we assume that the alphabet Σ is totally ordered, and that an order comparison takes constant time. For a string X, we define its leftmost minimum as the (positioned) character X[j], where j=min{i[1,|X|]:X[i]=mink[1,|X|]X[k]}. In other words, j is the leftmost position at which the minimum character in X occurs.

Cartesian Trees

In this work, consistent with the literature, we ensure that Cartesian trees are uniquely defined by resolving ties in favour of leftmost positions.

Definition 3.

The Cartesian tree of a string X, denoted by CT(X), is a rooted ordered binary tree with |X| nodes. The Cartesian tree of an empty string is the order-zero graph. For a non-empty string X, CT(X) is the tree obtained by creating a root node and (recursively) attaching to it CT(X[1..j)) as a left subtree and CT(X(j..|X|]) as a right subtree, where X[j] is the leftmost minimum of X.

Definition 4.

We say that a string X CT-matches a string Y (or that X and Y CT-match) if and only if CT(X)=CT(Y). We denote that two strings X and Y CT-match by writing XY and that they do not CT-match by writing XY.

Fact 5.

The CT-equivalence relation () is a transitive relation. That is, for any three strings X, Y, and Z, if XY and YZ, then XZ as well.

For strings T[1..n] (the text) and P[1..m] (the pattern), we say that i[1,nm+1] is a CT-occurrence of P in T (or that P CT-occurs in T at position i) if PT[i..i+|P|). The CT-matching problem consists in computing all CT-occurrences of P in T.

Lemma 6 ([29]).

Given a text T[1..n] and a pattern P[1..m], all CT-occurrences of P in T can be computed in 𝒪(n+m) time.

Lemma 7 ([29]).

Given a text T[1..n] and patterns P1[1..m1],,Ph[1..mh], all the CT-occurrences of all the patterns in T can be computed in 𝒪((n+i=1hmi)logh) time.

For equal-length strings X and Y, CHd(XY) denotes the minimum number of substitutions needed to transform X into a string X such that XY. We further define CHdk(XY)=min{k+1,CHd(XY)}. Given a text T[1..n] and a pattern P[1..m], we say that P has a k-approximate CT-occurrence at a position i[1,nm+1] of T if CHd(T[i..i+m)P)k.

The following fact states that CT-matching is a substring consistent equivalence relation.

Fact 8 (Theorem 2, [29]).

For any strings U and V with UV, we have U[i..j]V[i..j] for all i,j[1,|U|].

There is a natural bijection between positions of a string X and nodes in CT(X). We formalise this concept using the previous-smaller-or-equal-value function. For a string X, we define

psvX: [1,|X|][0,|X|), imax({j[1,i)X[j]X[i]}{0}).

The parent-distance representation PD(X) of a string X (see [29]) is a length-|X| string with

PD(X)[i]={ipsvX(i) if psvX(i)0;0otherwise.

Intuitively, we have psvX(i)=j if and only if the left subtree of the node corresponding to X[i] in CT(X) is CT(X(j..i)). Given either of psvX and PD(X), one can (recursively) construct CT(X), and hence the following lemma holds.

Lemma 9 ([29, Theorem 1]).

For equal-length strings X and Y, XY if and only if PD(X)=PD(Y), or equivalently i[1,|X|]:psvX(i)=psvY(i).

We provide an example of a Cartesian tree CT(X), the function psvX, the array PD(X), and the distance function CHd in Figure 2.

Figure 2: The Cartesian tree CT(X) of X=[4,5,6,1,2,7,7,8,3,9] (top left), the tree induced by psvX (top right), and the values of psvX, nsvX, PD(X), and ND(X) (bottom right). For Y=[14,15,16,11,12,17,17,18,13,19], we have XY, illustrating that different sequences can yield the same Cartesian tree. In contrast, the Cartesian tree of Z=[14,15,16,16,12,17,17,18,8,19] (bottom left) is different, i.e., we have ZX. However, we have CHd(XZ)=2 because we can substitute the values of X at positions 4 and 9 to obtain X=[4,5,6,𝟔,2,7,7,8,𝟏,9]Z.

For a string X, analogously to psvX, we define the next-smaller-value function, which captures the structure of the Cartesian tree as well:

nsvX: [1,|X|][2,|X|+1], imin({j(i,|X|]X[j]<X[i]}{|X|+1}).

We also define a length-|X| string ND(X) by

ND(X)[i]={nsvX(i)i,if nsvX(i)|X|+1,0,otherwise.

An analogue of Lemma 9 for nsvX and ND(X) is provided in the full version.

3 Cartesian Periodicity

Several definitions of periodicity for strings with respect to Cartesian tree matching have been studied (see [23, 29]). Here, we use the following definitions.

Definition 10 ([23]).

A string P[1..m] has a CT-border-period p[1,m] if and only if P[1..mp]P(p..m].

Lemma 11.

The leftmost minimum of a string P[1..m] with CT-border-period p[1,m2] lies outside P(p..mp].

Proof.

Assume that i(p,mp] is the position of the leftmost minimum of P. Then P[i] is also the leftmost minimum of both P[1..mp] and P(p..m], and hence it is the root of both CT(P[1..mp]) and CT(P(p..m]). However, in this case, the left subtree under the root of CT(P[1..mp]) is of size i1, while the the left subtree under the root of CT(P(p..m]) is of size ip1. This contradicts the assumption that P[1..mp]P(p..m].

Definition 12.

A string P[1..m] has a CT-block-period p[1,m] if and only if

  • p divides m,

  • p is a CT-border-period of P, and

  • the leftmost minimum of P is either P[1] or P[m].

 Remark 13.

The above definition restricts the definition of a full period from [29] by imposing the third condition. This condition crucially ensures that, for a CT-block-periodic fragment X[i..j] of a string X, either psvX[k][i,j) for all k(i,j] or nsvX[k](i,j] for all k[i,j), thus providing locality guarantees.

Lemma 14.

Given P[1..m] and a positive integer p<m/3 that is a CT-border-period of P, we can compute a fragment of length at least m2p that has CT-block-period p in 𝒪(p) time.

Proof.

Fact 8 implies that any substring of P of length at least p has CT-border-period p. Let m=pmp2p and note that p<m2pm<mp. By Lemma 11, there exists an offset a[0,p) such that the leftmost minimum of P is either P[1+a] or P[ma]. If the leftmost minimum is P[1+a], then the fragment P[1+a..m+a] has CT-block-period p. Otherwise, the fragment P(mam..ma] has CT-block-period p.

Lemma 15.

Consider a string P[1..m] that has a CT-block-period p[1,m2) and such that P[1] is the leftmost minimum of P[1..mp]. For i[1,m/p], let ci=(i1)p+1. For all i[1,m/p], P[ci] is the leftmost minimum of P[ci..m].

Proof.

For i[1,m/p] denote Pi:=P[ci..m]. We prove by induction the more general statement that p is a CT-block-period of Pi for all i with Pi[1] being the leftmost minimum of Pi. The induction hypothesis holds for i=1 since P[1] is the leftmost minimum of P[1..mp] and is therefore smaller than P[p+1] (since p<m/2), where P[p+1] is the leftmost minimum of P[p+1..m]. Now, consider any i[2,m/p] and suppose that p is a CT-block-period of Pi1 with Pi1[1] being the leftmost minimum of Pi1. First, since p is a CT-block-period of Pi1, we have Pi1[1..|Pi|]Pi and hence the leftmost minimum of Pi is Pi[1]. Further, Fact 8 implies that

P[ci..mp]=Pi1[1+p..|Pi1|p]Pi1[1+2p..|Pi1|]=P[ci+p..m]

and hence p is a CT-border-period of Pi. Finally, since p divides |P|, it also divides |Pi|=|P|(i1)p. This completes the induction and the statement follows.

An analogue of Lemma 15 for the case when P[m] is the leftmost minimum of P is given in the full version.

Fact 16.

Consider a string X. The parent-distance representation of a fragment X[i..j] of X is given by, for t[1,ji+1],

PD(X[i..j])[t]={0,if PD(X)[i+t1]t,PD(X)[i+t1],otherwise.

If X[i] is a leftmost minimum of X[i..j], then PD(X)(i..j] is a suffix of PD(X[i..j]).

Lemma 17.

Consider a string X and a fragment X[i..j] with leftmost minimum X[i]. Then, p<ji+1 is a CT-block-period of X[i..j] if and only if p is a period of PD(X)(i..j] and p divides ji+1.

Proof.

(:)

By the definition of a CT-block-period, we have that p divides ji+1 and that X[i..jp]X[i+p..j]. By Lemma 9, this equality implies that

PD(X[i..jp])=PD(X[i+p..j]). (1)

Further, by Fact 16, since X[i] and X[i+p] are the leftmost minima of X[i..jp] and X[i+p..j], respectively, we have that PD(X)(i..jp] is a suffix of PD(X[i..jp]) and that PD(X)(i+p..j] is a suffix of PD(X[i+p..j]). By (1), we then have PD(X)(i..jp]=PD(X)(i+p..j] and hence p is a period of PD(X)(i..j].

(:)

We first argue that it suffices to show that X[i+p] is the leftmost minimum of X[i+p..j]. If this is indeed the case, we have that PD(X)(i+p..j]=PD(X)(i..jp] is a suffix of PD(X[i+p..j]) which, together with the fact that PD(X[i..jp])[1]=0=PD(X[i+p..j])[1], implies that PD(X[i..jp])=PD(X[i+p..j]) and hence that X[i..jp]X[i+p..j] by Lemma 9. Since p divides ji+1 and X[i] is the leftmost minimum of X[i..j], p is a CT-block-period of X[i..j].

Now, suppose for the sake of contradiction, that the leftmost minimum of X[i+p..j] is at some position z(i+p,j]. Then, psvX(z)=zPD(X)[z]<i+p. Since X[i] is the leftmost minimum of X[i..j], psvX(z)[i,i+p). Since PD(X(i..j]) is periodic with period p, we have PD(X)[z]=PD(X)[zp]. Therefore, our assumption implies that psvX(zp)=(zp)PD(X)[zp]=psvX(z)p<i, which contradicts the assumption that X[i] is the leftmost minimum of X[i..j].

An analogue of the above lemma for the case when the leftmost minimum of X[i..j] is X[j] is given in the full version.

Corollary 18.

For equal-length strings X and Y that have a common CT-block-period p[1,|X|/2], we have XY if and only if X[1..2p]Y[1..2p].

Proof.

(:)

This implication follows directly from Fact 8.

(:)

Due to Lemma 15 and its analogue, both X and Y have their leftmost minima at the same position (since X[1..2p] and Y[1..2p] do). For the remainder of the proof, we assume that these minima occur at the first positions, noting that the remaining case can be handled symmetrically. Since X[1..2p]Y[1..2p], Lemma 9 yields that PD(X[1..2p])=PD(Y[1..2p]). Further, we have PD(X[1..2p])=PD(X)[1..2p] and PD(Y[1..2p])=PD(Y)[1..2p] by Fact 16. Hence, PD(Y)[1..2p]=PD(X)[1..2p]. Since p is a CT-block-period of each of X and Y, by applying Lemma 17 to each of X and Y, we conclude that p is a period of both PD(X)(1..|X|] and PD(Y)(1..|Y|]. This directly implies that PD(X)=PD(Y), and we hence have XY by Lemma 9.

Lemma 19.

Suppose that a fragment X[i..j) has minimum CT-block-period p. Then, for any a,b[i,j] such that ai(modp), bj(modp), and ba2p, we have that X[a..b)X[i..i+(ba)) and that X[a..b) has minimum CT-block-period p.

Proof.

Without loss of generality, assume that X[i] is the leftmost minimum of X[i..j). The complementary case when X[j1] is the leftmost minimum can be handled in a symmetric manner using the analogues of the lemmas used below.

Fix a,b satisfying the conditions of the claim. If ai, then the CT-border-period p of X[i..j) implies that X[a..b)X[ap..bp)X[i..i+(ba)).

Now, observe that X[a] is the leftmost minimum of X[a..j) by Lemma 15. Additionally, we have X[a..bp)X[a+p..b) by Fact 8 because p is a CT-border-period of X[i..j). Finally, p divides ba by our assumptions and hence p is a CT-block-period of X[a..b).

It remains to show that p is the minimum CT-block-period of X[a..b). Towards a contradiction suppose that X[a..b) has minimum CT-block-period q<p. Then, by Lemma 17, PD(X)(a..b) has a period q and PD(X)(i..j) has a period p. Since the length of the fragment is ba2p>p+q, an application of the Periodicity Lemma (Lemma 2) yields that PD(X)(a..b) has period gcd(p,q). Consequently, PD(X)(i..j) also has period gcd(p,q). Another application of Lemma 17 implies that X[i..j) has CT-block-period gcd(p,q)<p (since gcd(p,q) divides the length ji), a contradiction.

Definition 20.

Let X be a string. A fragment X[i..j] with minimum CT-block-period p(ji+1)/2 is called a CT-run if and only if p is not a CT-block-period of X[ip..j] (or ip<1) and p is not a CT-block-period of X[i..j+p] (or j+p>|X|).

The occurrences of a periodic pattern P in a text T form arithmetic progressions with each such progression corresponding to a run with period per(P). We show an analogous result for CT-occurrences.

Example 21.

Consider a pattern P=[10,40,30,20,60,50]. P is of length 6 and has a CT-block-period p:=3. The leftmost minimum of P is at its first position. The parent-distance array for P is PD(P)=[0,1,2,3,1,2].

Consider the text T=[100,400,300,200,600,500,300,800,700,900] of length n=10. The parent-distance array for T is: PD(T)=[0,1,2,3,1,2,3,1,2,1].

There are two CT-occurrences of P in T:

  • at position 1, T[1..6]=[100,400,300,200,600,500], where PD(T[1..6])=[0,1,2,3,1,2];

  • at position 4, T[4..9]=[200,600,500,300,800,700], where PD(T[4..9])=[0,1,2,3,1,2].

Note that the fragment T[1..9] forms a CT-run in T with minimum CT-block-period p=3.

Lemma 22.

Let P be a pattern of length m with minimum CT-block-period pm/4, and let T be a text of length n. The exact CT-occurrences of P in T can be partitioned into 𝒪(n/m) maximal arithmetic progressions with common difference p. For each such progression {u+vp:v[0,z]}, the fragment T[u..u+zp+m) is a CT-run with minimum CT-block-period p. For any two such arithmetic progressions {u1+vp:v[0,z1]} and {u2+vp:v[0,z2]}, the two runs T[u1..u1+z1p+m) and T[u2..u2+z2p+m) overlap by fewer than p positions.

Proof.

We henceforth assume that the leftmost minimum of P is at its first position. The proof for the complementary case, that is, when the leftmost minimum of P is P[m], is symmetric (using ND instead of PD and the analogous versions of the used lemmas).

Let P:=PD(P)(1..m]. By the CT-block-periodicity of P and Lemma 17 we have per(P)=p. Since P[1] is the leftmost minimum of P, Fact 16 and 9 imply that P CT-occurs at some position x in T if and only if the following two conditions hold:

  • PD-match condition: PD(T)(x..x+m)=P;

  • left-min condition: T[x] is the leftmost minimum of T[x..x+m).

Claim 23.

Consider a maximal arithmetic progression D={j+ip:i[0,s]} of occurrences of P in PD(T). For i[0,s], denote di:=j+ip. Then, either P does not have any CT-occurrence at a position of T in D1, or there exists an integer μ[0,s] such that both of the following hold:

  • the intersection of the set of CT-occurrences of P in T and D1 is {di1:i[μ,s]};

  • T[dμ1..ds1+m) is a CT-run with minimum CT-block-period p.

Proof.

By the definition of D, we have PD(T)(x..x+m)=P for all xD. Hence, the PD-match condition holds for all xD1. If the left-min condition fails for every element of D1, then P does not have any CT-occurrence at any position of T in D1, and the claim follows. Otherwise, let μ=min{i[0,s]:T[di1] is a minimum in T[di1..di1+m)}. We show by induction that the left-min condition holds for all x{di1:i[μ,s]}. The base case y=μ holds by definition. Assume that it holds for some y[μ,s). An application of Lemma 15 to T[dy1..dy+11+m) implies that T[dy+11] is the leftmost minimum of T[dy+11..dy+11+m). This completes the proof of the inductive step and hence concludes the proof of the first item. Let F:=T[dμ1..ds1+m). By repeatedly applying Lemma 15, we conclude that the leftmost minimum of F is F[1], and hence that p is a CT-block-period of F. If F had a smaller CT-block-period, then, by Lemma 19, the same would hold for P, contradicting the assumption that P has minimum CT-block-period p. Finally, we cannot prepend or append p characters to F while maintaining that it has CT-block-period p: either the obtained string does not have its leftmost minimum at its first position or we contradict the maximality of D. This concludes the proof of the claim.

To complete the proof, it suffices to combine Claim 23 with the fact that a CT-occurrence of P in T at position j implies an occurrence of P in PD(T) at position j+1, noting that the occurrences of P in PD(T) can be partitioned into 𝒪(n/m) maximal arithmetic progressions with period per(P)=p such that any two elements from distinct arithmetic progressions differ by more than mp (see [3, 11]).

4 Approximate CT-Matching with Substitutions

Kim and Han [21] recently presented a dynamic programming algorithm that, given two strings X and Y, computes the minimum cost of a sequence of edit operations (insertions, deletions, and substitutions) required to transform X into a string X such that XY. As noted in [21, Section 6], a minor modification to their algorithm results in the following lemma for the special case when only substitutions are allowed.

Lemma 24 (see [21]).

Given two strings T[1..m] and P[1..m], and an integer threshold k>0, we can compute CHdk(TP) in 𝒪(mk) time.

In the full version, we provide a self-contained proof of Lemma 24 for the sake of completeness.

4.1 Analysing the Pattern

Definition 25.

A set 𝒮 of equal-length strings is a CT-rainbow if and only if there do not exist distinct S1,S2𝒮 such that S1S2.

Lemma 26.

Let m,Δ+ with Δ<m/2. Given Δ and a string P[1..m], in 𝒪(mΔ) time, we can either compute a set of Δ disjoint fragments of P, each of length m/(2Δ), that form a CT-rainbow or report a fragment of length at least m/(4Δ) that has a CT-block-period less than Δ, together with its minimal CT-block-period.

Proof.

Let m=m/(2Δ). We process P in a left-to-right manner, attempting to identify m-length fragments to insert into an initially empty set 𝒮, which will remain a CT-rainbow throughout. Whenever a fragment is inserted into 𝒮, we find and mark all of its exact CT-occurrences in P in 𝒪(m) time using Lemma 6. For each inserted fragment, we use a unique symbol for marking.

We first insert fragment P[1..m] into 𝒮. Let P[i..i+m) be the fragment that was most recently inserted into 𝒮 and assume that |𝒮|<Δ (otherwise, we return 𝒮 and terminate the algorithm). Our goal is to then find some j[i+m..i+m+Δ) such that P[j..j+m) does not CT-match any element of 𝒮. To do this, it suffices to find, in 𝒪(Δ) time, the first unmarked position in [i+m..i+m+Δ), if one exists. If we can always find such a position j while |𝒮|<Δ, then we eventually insert Δ fragments into 𝒮. This holds because the total length of the fragments inserted into 𝒮 and the lengths of the gaps between them add up to at most Δ(m+Δ1)m/2+Δ2m since the length of the gap between any two consecutive fragments is less than Δ and Δ<m/2. Inserting a fragment into 𝒮 and marking all of its exact CT-occurrences takes 𝒪(m) time. In the case when we can always find a fragment to insert into 𝒮, the algorithm thus runs in 𝒪(mΔ) time.

Now consider the complementary case when, after inserting some fragment P[i..i+m) into 𝒮, we have |𝒮|<Δ and all positions in [i+m..i+m+Δ) are marked. Then, by the pigeonhole principle, some fragment in 𝒮 has two CT-occurrences at positions i1<i2 in [i+m..i+m+Δ) with q:=i2i1<Δ. We find two such positions (marked with the same symbol) naively in 𝒪(Δ2)𝒪(m) time. Let G=P[i1..i2+m). G has length L=m+q and CT-border-period q. We apply Lemma 14 to trim G. Both conditions of the lemma are satisfied since Δ>q, mm/(2Δ), and Δ<m/2, and hence

L=m+qm/(2Δ)+q>m+q2Δ+q>3q.

Trimming G yields a fragment F with CT-block-period q and length

|F|L2q=mqm/(2Δ)Δ>m/(2Δ)m/2m/(4Δ).

Finally, we naively compute the smallest CT-block-period p of F by checking each integer in [1,q1] in 𝒪(m) time, for a total running time of 𝒪(mΔ), and return the pair (F,p).

4.2 The Aperiodic Case

In this section, we deal with the (easy) case when the analysis of the pattern according to Lemma 26 returns a large CT-rainbow of disjoint fragments. We apply a standard marking trick: an exact CT-occurrence of a fragment P[a..b]𝒮 at a position j in T contributes a mark to position ja+1, indicating a potential starting position of a k-approximate CT-occurrence of P in T. The following simple fact captures the key property we use: if CHdk(T[i..i+m)P)k, then position i must receive at least Δk marks.

Lemma 27.

Let k,Δ+ with Δk. Consider strings V,U satisfying CHdk(VU)k. Let 𝒰={U[ai..bi]:i[1,Δ]} be a set of disjoint fragments of U. Then there exists a set I[1,Δ] of size at least Δk such that V[ai..bi]U[ai..bi] for all iI.

Proof.

Let V be a string obtained from V by substituting at most k characters such that VU. Let I:={i[1,Δ]:V[ai..bi]=V[ai..bi]}. Set I is of size at least Δk as the substitutions transforming V into V affect at most k fragments V[ai..bi]. For each iI, Fact 8 implies that V[ai..bi]U[ai..bi]. Moreover, for each iI, we have V[ai..bi]=V[ai..bi] and hence the claim follows.

In the following lemma, we use the marking trick to efficiently compute a small number of candidate positions that need to be verified, and verify them using Lemma 24.

Lemma 28.

Let n,m,k,Δ+ with n3m/2 and 2kΔm/2. Given k, a text T[1..n], and a pattern P[1..m], together with a CT-rainbow 𝒫 consisting of Δ disjoint fragments of P, each of length m/2Δ, we can compute CHdk(T[i..i+m)P) for all i[1,nm+1] in 𝒪(m2k/Δ) time.

Proof.

We perform multiple-pattern CT-matching in T for all fragments of 𝒫 in 𝒪(mlogm)𝒪(m2k/Δ) time using Lemma 7. If a fragment P[a..b]𝒫 CT-matches a fragment T[i..j], we add a mark at position ia+1 of T. By the fact that 𝒫 is a CT-rainbow and transitivity (Fact 5), at most one fragment of 𝒫 can CT-match at any position of T. Hence, the total number of marks is 𝒪(m). Furthermore, Lemma 27 implies that if CHdk(T[i..i+m)P)k, then position i must receive at least ΔkΔ/2 marks. There are 𝒪(m/Δ) such positions, which can be identified at no additional cost during the marking process. Each of these positions is then verified in 𝒪(mk) time using Lemma 24, yielding a total verification time of 𝒪(mkm/Δ)=𝒪(m2k/Δ).

4.3 The Periodic Case

In this section, we address the (much more complicated) case when the analysis of the pattern according to Lemma 26 returns a long fragment with a small CT-block-period.

We first establish combinatorial lemmas that allow us to trim both P and T[i..i+m) under certain conditions before applying Lemma 24. Intuitively, whenever a long CT-block-periodic fragment of T is aligned with a corresponding periodic fragment of P, substitutions are not required in (a long part of) this fragment. This trimming improves computational efficiency, as the complexity of Lemma 24 depends on the lengths of the input strings.

Figure 3: An illustration of the settings in Lemmas 29 and 31 with k=3. The psvY array is shown with grey arrows below string Y. Lemma 29 establishes that any sequence of CHd(XY) substitutions that transforms X into X such that XY does not modify the fragment highlighted in red; the condition “i[cr+p,|Y|]:psvY(i)[c1,cr)” ensures that none of these substitutions “interact” with this fragment. Lemma 31 establishes that we can trim a pair of fragments (one in X and one in Y) without altering the value of CHd(XY).
Lemma 29.

Consider p,r,k+ and strings X=X1UX2 and Y=Y1VY2 such that all of the following hold:

  • |X1|=|Y1|, |X2|=|Y2|, and |U|=|V|=rp, where r2k+1;

  • UV;

  • there is no position i[|Y1V|+1..|Y|] such that psvY(i)[|Y1|+1..|Y1V|p];

  • if we define i[1,r]:ci:=|X1|+(i1)p+1, then X[ci] is a minimum in X[ci..cr+p), and Y[ci] is a minimum in Y[ci..cr+p);

  • CHd(XY)k.

Any sequence of CHd(XY) substitutions that transforms X into X with XY does not perform any substitution in fragment X[ck+1..crk].

Proof.

Consider any sequence of CHd(XY) substitutions that transforms X into X such that XY. We fix i,j[1,r] to be the minimal and maximal values, respectively, such that X[ci] and X[cj] are not modified. (There are at least two distinct values because rCHd(XY)+2.) We show that no substitution is performed in X[ci..cj].

Let Z=X[1..ci)X[ci..cj]X(cj..|X|]=X[1..ci]X(ci..cj)X[cj..|X|]. We claim that ZY. If not, there would exist x[1,|X|] with psvZ(x)psvY(x). We show that such x does not exist by distinguishing between the following four cases:

Case 1:

x[1,ci]. Since Z has prefix X[1..ci], and due to XY, Fact 8, and Lemma 9, we have x[1,ci]:psvZ(x)=psvX(x)=psvY(x).

Case 2:

x(ci,cj]. Y[ci] is minimal in Y[ci..cr] by assumptions. Hence, psvY(x)ci. We obtain psvZ(x)=psvY(x) due to Lemma 9 and the observation that:

Z[ci..cj]=X[ci..cj]=U(ipp..jpp+1]V(ipp..jpp+1]=Y[ci..cj].
Case 3:

x(cj,cr+p). Since Y[cj] is minimal in Y[cj..cr+p), we have psvY(x)cj. Therefore, psvZ(x)=psvX(x)=psvY(x) follows from Z[cj..cr+p)=X[cj..cr+p)Y[cj..cr+p).

Case 4:

x[cr+p,|X|]. By the assumptions, we have psvY(x)[|Y1|+1,|Y1V|p]=[c1,cr). First, consider the case when psvY(x)cr. Note that cjcr implies Z[cr..|X|]=X[cr..|X|]. Hence, psvZ(x)=psvX(x)=psvY(x) follows from XY, together with Fact 8 and 9. If, however, psvX(x)=psvY(x)<c1ci, then clearly X[x]<X[ci]=X[ci]. Since X[ci]=Z[ci] is minimal in X[ci..cj)=Z[ci..cj), it cannot be that psvZ(x)[ci,cj), which implies psvZ(x)=psvX(x)=psvY(x).

We have shown that ZY. Hence, the considered sequence of substitutions did not modify X[ci..cj]. Finally, by the definition of i and j, the characters in positions c1,,ci1 and cj+1,,cr in X must have been modified. We therefore have (i1)+(rj)CHd(XY)k, which implies ik+1 and jrk. Consequently, there are no substitutions in X[ck+1..crk].

Lemma 30.

Consider strings X and Y with XY. Let a,b[1,|Y|] such that ab and Y[a] is minimal in Y[a..b]. Then X[1..a]X(b..|X|]Y[1..a]Y(b..|X|].

Proof.

The assumption that XY, together with Fact 8 and 9, imply that X[a] is minimal in X[a..b]. For Z{X,Y}, let Z^=Z[1..a]Z(b..|Z|]. It is easy to see that the following hold:

  • For i[1,a], psvZ^(i)=psvZ(i). (This is trivial.)

  • For i(a,|Z^|] with psvZ(i+ba)(b,|Z|], we have psvZ^(i)=psvZ(i+ba)b+a.

  • For i(a,|Z^|] with psvZ(i+ba)(a,b], we have psvZ^(i)=a.

  • For i(a,|Z^|] with psvZ(i+ba)[1,a], we have psvZ^(i)=psvZ(i+ba).

Note that the definition of psvZ^ depends only on the psvZ array. Since XY, we have that psvX=psvY by Lemma 9. Therefore, it follows that psvX^=psvY^. By applying Lemma 9 again, we conclude that X^Y^.

Lemma 31.

Consider p,r,k+ and strings X=X1UX2 and Y=Y1VY2 such that all of the following hold:

  • |X1|=|Y1|, |X2|=|Y2|, and |U|=|V|=rp, where r2k+3;

  • UV;

  • there is no position i[|Y1V|+1..|Y|] such that psvY(i)[|Y1|+1..|Y1V|p];

  • if we define i[1,r]:ci:=|X1|+(i1)p+1, then X[ci] is a minimum in X[ci..cr+p), and Y[ci] is a minimum in Y[ci..cr+p).

Then CHdk(X^Y^)=CHdk(XY), where

X^=X[1..ck+1]X(crkp..|X|]andY^=Y[1..ck+1]Y(crkp..|Y|].

Proof.

It suffices to prove the following two claims, which together imply the statement.

Claim 32.

CHd(XY)k implies CHd(X^Y^)CHd(XY).

Claim 33.

CHd(X^Y^)k implies CHd(X^Y^)CHd(XY).

Proof of Claim 32.

Assume that CHd(XY)k and consider any sequence of CHd(XY) substitutions that transform X into a string X with XY. By Lemma 29, we have X=X[1..ck+1)X[ck+1..crk]X(crk..|X|]. Note that we can perform the same sequence of substitutions (with an appropriate shift) on X^ as well. Hence, there is a sequence of CHd(XY) substitutions that transforms X^ into

X^:=X[1..ck+1)X[ck+1]X(crkp..crk]X(crk..|X|].

It remains to be shown that X^Y^, which implies CHd(X^Y^)CHd(XY). Note that X^ and Y^ can be obtained by deleting fragments X(ck+1..crkp] and Y(ck+1..crkp] from X and Y, respectively. By the definition of Y, we know that Y[ck+1] is a minimum in Y[ck+1..crkp]. Hence, we can apply Lemma 30 to X and Y with a=ck+1 and b=crkp, thus obtaining X^Y^.

Proof of Claim 33.

Assume that CHd(X^Y^)k and consider any sequence of CHd(X^Y^) substitutions that transform X^ into a string X^ with X^Y^. It can be readily verified that the strings X^ and Y^ still satisfy the conditions of Lemma 29 with parameter r^=2k+2. Therefore, we have:

X^= X^[1..ck+1)X^[ck+1..cr^k]X^(cr^k..|X^|]
= X^[1..ck+1)X[ck+1]X(crkp..crk]X^(ck+2..|X^|].

We observe that the same sequence of substitutions can also be applied directly to X, resulting in the string: X=X^[1..ck+1)X[ck+1..crk]X^(ck+2..|X^|].

It remains to be shown that XY, which implies CHd(X^Y^)CHd(XY). Note that X^ and X, as well as Y^ and Y, share a prefix of length ck+1. Due to X^Y^, combined with Fact 8 and 9, it is clear that, for every x[1..ck+1], psvX(x)=psvX^(x)=psvY^(x)=psvY(x).

Next, we observe that X[ck+1..crk]=X[ck+1..crk]. Recall that X[ck+1] and Y[ck+1] are minimal in X[ck+1..crk] and Y[ck+1..crk], respectively. Due to UV, combined with Fact 8 and 9, we have x(ck+1,crk]:psvX(x)=psvY(x)ck+1.

Finally, we consider x(crk,|X|]. Let x^=x|X|+|X^|. We observe that X^ and X, as well as Y^ and Y, share a suffix of length :=|X|crk+p. If psvY(x)>crkp, then X^Y^ already implies psvX^(x^)=psvY^(x^). It remains to consider the case when x(crk,|X|] and psvY(x)crkp. In this case, since Y[crk] is minimal in Y[crk..cr+p), it holds that xcr+p=|Y1V|+1, and, by the condition of the lemma, psvY(x)|Y1|=c11. Note that psvY^(x^)=psvY(x), as we obtained Y^ by merely deleting some elements between psvY(x) and x. Due to X^Y^, we have psvX^(x^)=psvY^(x^). Finally, we obtain X from X^ by inserting into X^ values that are at least as large as X^[ck+1]=X[ck+1] between positions psvX^(x^) and x^. Since X^[ck+1](psvX^(x^),x^), we know that X^[x^]<X^[ck+1], and thus all inserted values are at least X^[x^]. Thus, psvX(x)=psvX^(x^)=psvY^(x^)=psvY(x), as required.

The combination of the two claims yields that either both CHd(X^Y^) and CHd(XY) are at most k and are in fact equal, or they are both greater than k.

A symmetric claim holds for next-smaller-values. For completeness, we provide a proof of the corresponding lemma below in the full version.

Lemma 34 (analogue of Lemma 31).

Consider p,r,k+ and strings X=X1UX2 and Y=Y1VY2 such that all of the following hold:

  • |X1|=|Y1|, |X2|=|Y2|, and |U|=|V|=rp, where r2k+3;

  • UV;

  • there is no position i[1,|Y1|] such that nsvY(i)[|Y1|+p+1..|Y1V|];

  • if we define i[1,r]:ci:=|X1|+ip, then X[ci] is a minimum in X(c1p..ci], and Y[ci] is a minimum in Y(c1p..ci].

Then CHdk(X^Y^)=CHdk(XY), where

X^=X[1..ck+1+p)X[crk..|X|]andY^=Y[1..ck+1+p)Y[crk..|Y|].

We are now ready to prove the main algorithmic result of this section.

Lemma 35.

Let n,m,k,p,Δ+ satisfy n3m/2, p<Δ, k<Δ, and kΔm/128. Given k, p, Δ, a text T[1..n], a pattern P[1..m], and a fragment P[..r) of length at least m/(4Δ) with minimum CT-block-period p, we can compute CHdk(T[i..i+m)P) for all i[1,nm+1] in 𝒪(mk4Δ) time.

Proof.

Due to Δ2m/(1282k2), the fragment P[..r) is of length at least m/(4Δ)pm/(4Δ2)>p1000k2 and hence consists of at least 1000k2 blocks of length p; namely, P[+ip..+(i+1)p) for i[0,(r)/p). In any k-approximate CT-occurrence of P[..r) in T, at least 1000k2k999k2 of those blocks are aligned with fragments of T that CT-match them. These blocks are partitioned into at most k+1 sets of contiguous blocks by the at most k blocks that are aligned with fragments of T that do not CT-match them. Hence, in any k-approximate CT-occurrence of P[..r) in T, there exists a fragment F of P[..r) that consists of at least 999k2/(k+1)>100k blocks and is CT-matched exactly.222Note that it might be a different fragment for each k-approximate CT-occurrence of P[..r) in T. We have |F|=Ω(|P[..r)]|/k)Ω(m/(kΔ)). Further, the CT-block-periodicity of P[..r) implies that FP[..+|F|) and, combined with Lemma 19, that F has minimum CT-block-period p.

For a string X, a block X[i..i+p) of length p with ip,i+2p1[1,|X|], is bad if X[ip..i+2p)P[..+3p) and good otherwise. Intuitively, if we have many bad blocks in P, at least one of them has to be aligned with a bad block in the text. In this case, we exploit this property to obtain a few candidate starting positions of k-approximate CT-matches. We then verify each of them using Lemma 24. In the complementary case, the pattern is almost periodic (that is, it almost entirely consists of good blocks). We exploit this by trimming long pairs of fragments (one in T and one in P) that are composed solely of good blocks using either Lemma 31 or Lemma 34 before invoking Lemma 24.

We compute a fragment Φ=P[..r) of P by extending P[..r) blockwise to the left (and to the right) by prepending (resp. appending) blocks of p characters until we either accumulate 3k+1 bad blocks in that direction or there are fewer than 2p characters left in that direction – in the latter case, we almost reach the beginning (resp. end) of P.

​​

Figure 4: Illustrations for Lemma 35. Gray (hatched) blocks are explicitly (resp., implicitly) bad.

Case I: Enough blocks accumulated in at least one direction.

Assume, without loss of generality, that we accumulated 3k+1 bad blocks while extending P[..r) to the left.

We employ the linear-time exact CT-matching algorithm of Lemma 6 to compute all exact CT-occurrences of F:=P[..+100kp) in T. By Lemma 22, these CT-occurrences can be partitioned into 𝒪(n/|F|)𝒪(kΔ) arithmetic progressions with common difference p such that the CT-occurrences in each of the progressions span a CT-run of length Ω(m/(kΔ)) with minimum CT-block-period p. Let denote the set of CT-runs in T that are spanned by the exact CT-occurrences of F.

Let us fix a CT-run T[a..b]=R. We extend R to the left using a procedure identical to the one performed on P[..r) until we either accumulate 3k+1 bad blocks or the fragment contains T[2p]. Consider aligning the pattern with a fragment T[i..i+m) such that a fragment of P[..r) that CT-matches F is aligned with a fragment of R that CT-matches it. By Lemma 22, any such alignment satisfies ai+1(modp), that is, it perfectly aligns the block boundaries of P[..r) and R. In such an alignment, if a bad (resp. good) block of the pattern is aligned with a good (resp. bad) block of the text, at least one substitution is required in either that text block or one of its two neighbours in any sequence of substitutions that transforms T[i..i+m) into a string XP. Thus, k substitutions performed on T[i..i+m) can fix at most 3k misaligned pairs (that is, pairs consisting of a bad block in one of the strings and a good block in the other). Therefore, at least one of the leftmost 9k+1 bad blocks of Φ must be aligned with one of the at most 3k+1 bad blocks in the extension of R. There are only 𝒪(k2) ways to align such a pair of bad blocks, each yielding a candidate starting position of a k-approximate CT-occurrence of P in T. The described procedure can be implemented naively in 𝒪(m) time.

We perform this procedure for all CT-runs in , thus obtaining 𝒪(||k2)=𝒪(k3Δ) candidate starting positions. We then invoke Lemma 24 for each such position. In total, this takes time 𝒪(k3Δmk)=𝒪(mk4Δ).

Case II: The pattern is almost CT-block-periodic.

In the complementary case, we did not accumulate 9k+1 bad blocks in either direction. Thus, P=XPBPYP where |XP|,|YP|<2p and BP consists of p-length blocks, at most 6k of which are bad.

Claim 36.

In 𝒪(n) time, we can either decide that P has no k-approximate CT occurrences in T or compute a fragment T=T[t1..t2)=XTBTYT such that the following hold:

  • for all i[1,nm+1], CHdk(T[i..i+m)P)k, implies that i,i+m[t1,t2] and it1(modp).

  • |XT|=|XP| and |YT|=|YP|,

Moreover, BT is partitioned into p-length blocks 𝒪(k) of which are explicitly marked as bad.

Proof.

By Lemma 19, the fragment Π:=P[..+3p) has minimum CT-block-period p. Thus, by Lemma 22, any two exact CT-occurrences of Π in T are at distance at least p and there are at most n/p CT-occurrences in total.

Now, any k-approximate CT-occurrence of P in T implies a large number of exact CT-occurrences of Π at positions that are in a single equivalence class modulo p, with each such CT-occurrence corresponding to aligning a good block of BP with a fragment of T. Specifically, by accounting for the at most k substitutions (each potentially affecting three good blocks), the at most 6k bad blocks in P, as well as XP and XT which are of total length at most 4p, we conclude that we must have at least (m4p)/p6k3km/p13k such exact CT-occurrences. The inequalities kΔm/128 and p<Δ imply that 13kp<m/4, and hence m/p13k(mm/4)/p. Since we have a total of n/p CT-occurrences of Π in T and n/p3m/(2p)<2(mm/4)/p, there is at most one residue modulo p, say ρ, with at least m/pm/p CT-occurrences of Π starting at a positions equivalent to ρ modulo p.

We compute all exact CT-occurrences of Π in T in 𝒪(n) time using Lemma 6 and identify the majority residue modulo p, say ρ, resolving ties arbitrarily. If the CT-occurrences of Π at positions of T equivalent to ρ modulo p are fewer than m/pm/p, we conclude that P does not have any k-approximate CT-occurrences in T and terminate the algorithm. We henceforth, assume that we are in the complementary case.

We select y as the leftmost position in T such that yn/2 and yρ(modp). We extend the fragment T[y..y+p) in each direction until we either accumulate 9k+1 bad blocks or there are fewer than 2p characters left. Let T[a..b) denote the obtained fragment.

Any k-approximate CT-occurrence T[i..i+m) of P in T must align BP with a fragment of the form T[a+ip..bjp) for nonnegative integers i and j. Further, in this CT-occurrence, BP must be aligned with a fragment of T that contains T[n/2]. Now, observe that at most 9k bad blocks of T can be contained in T[i..i+m), as at most 6k of them can be aligned with CT-matching bad blocks of P and the at most k substitutions may fix at most 3k pairs of bad blocks in T with good blocks in P. This implies that i+|XP|,i+|XPBP|[a,b].

Next, we define the boundaries t1 and t2, and describe the decomposition T=XTBTYT. Let t1 be the smallest positive integer in {a+ip|XP|:i{0,1,2}}, let t2 be the largest integer in {bip+|YP|:i{0,1,2}}[1,n], and set T=T[t1..t2). Since, for any approximate CT-occurrence T[i..i+m) we have i+|XP|,i+|XPBP|[a,b], this ensures that i,i+m[t1,t2]. Further we have that it1(modp) since i+|XP|a(modp). The partition of T is then defined as: XT=T[t1..t1+|XP|), BT=T[t1+|XP|..t2|YP|), YT=T[t2|YP|..t2). Finally, we return t1, t2, and the bad blocks in BT.

We also designate each block in BP as implicitly bad if it contains a position i such that there exists a position j in either an explicitly bad block or in J:=[1,|XP|](|XPBP|,|P|], such that i=psvP(j) or i=nsvP(j). Note that the number of implicitly bad blocks is 𝒪(kp)𝒪(kΔ) (since p<Δ) as each (explicitly) bad block implies 𝒪(p) implicitly bad ones and J implies 𝒪(p) implicitly bad blocks. This designation is necessary because substitutions are local operations, whereas CT-equivalence is a global property. Although substitutions directly modify values within explicitly bad blocks, a single substitution can indirectly affect many distant positions. In particular, if a substitution occurs at position i such that i=psvP(j) or i=nsvP(j) for some position j, then the values psvP(j) or psvP(j) may change. To ensure that Lemma 31 can be invoked to trim long sequences of good blocks, we must account for all blocks that could potentially interact with either the boundary fragments or the blocks aligned with blocks that contain substitutions.

By Claim 36, it suffices to compute CHdk(T[i..i+m)P) for each of the 𝒪(m/p) positions in T that satisfy it1(modp) and i,i+m[t1,t2]. Let G=T[i..i+m). G inherits its block-decomposition from BT, as well as the classification of some blocks as bad. We call the considered position i an overlap position if there exist positions π in P and ϕ in G that belong to (implicitly or explicitly) bad blocks and satisfy |πϕ|6kp, and a non-overlap position otherwise. We treat overlap and non-overlap positions differently:

  • If i is an overlap position, we employ Lemma 24 to compute CHdk(GP) in 𝒪(mk) time. The number of overlap positions is 𝒪(k3p)=𝒪(k3Δ) since we require one of the 𝒪(kp) (implicitly or explicitly) bad blocks in BP to be within 𝒪(k) blocks of one of the 𝒪(k) bad blocks in BT. The total time required for overlap positions is thus 𝒪(mk4Δ). Note that we can efficiently enumerate all the overlap positions using the list of bad blocks for both BP and BT.

  • If i is a non-overlap position, then we can show that CHdk(GP) only depends on the parts of the alignment of G and P in the 𝒪(k)-block vicinity of the (implicitly or explicitly) bad blocks. More precisely, Lemmas 31 and 34 will allow us to delete most of the good blocks, significantly reducing the lengths of G and P prior to performing the comparison of Lemma 24. We first describe this trimming procedure, and then justify that the conditions for Lemmas 31 and 34 are indeed satisfied.

    We use Lemma 31 if P[] is the leftmost minimum of Φ and Lemma 34 otherwise, that is, if the leftmost minimum is P[r1]. Conceptually, we perform the following procedure. We traverse the lists of bad blocks in each of G and P from left to right in parallel in 𝒪(k) time. Whenever we encounter a maximal pair of fragments U=G[x1..x2) and V=P[x1..x2) of length at least (6k+1)p that only consist of blocks that are not (implicitly or explicitly) bad, we replace G[x1..x2) with U[1..3kp]U(|U|3kp..|U|] and P[x1..x2) with V[1..3kp]V(|V|3kp..|V|]. A repeated application of either Lemma 31 or Lemma 34 guarantees that CHdk(GP)=CHdk(GP), where G and P are the strings obtained from G and P, respectively. Instead of making the replacements on G and P, we explicitly construct G and P by copying the fragments of G and P that are not deleted by the conceptual procedure described above.

    As we have 𝒪(kp) (implicitly or explicitly) bad blocks in P and 𝒪(k) bad blocks in G, and since each bad block prevents 𝒪(k) blocks from being trimmed, we have |G|=|P|=𝒪(k2p2). The computation of CHdk(GP) using Lemma 24 thus takes 𝒪(k2p2k) time and returns CHdk(GP). Over all 𝒪(m/p) non-overlap positions, the total time required is 𝒪(m/pk2p2k)=𝒪(mpk3)=𝒪(mk3Δ).

    It remains to be shown that the described applications of Lemma 31 are valid if P[] is the leftmost minimum of Φ; applications of Lemma 34 are valid in the remaining case by symmetric arguments. First, note that p is a CT-block-period of U and V by Lemma 22, and they both have their leftmost minimum at their first positions.

    • The first condition of Lemma 31 holds trivially by our assumptions with r=(x2x1)/p.

    • The second condition of Lemma 31 holds by Corollary 18 as p is a CT-block-period of both U and V, and U[1..2p]P[+p..+3p)V[1..2p].

    • The third condition of Lemma 31 holds due to the facts that (a) by the definition of implicitly bad blocks, there is no position j outside a good block with psvP(j)[x1..x2p), and (b) for each position j in a good block, psvP(j) is at least jp by an application of Lemma 15 to Φ.

    • The fourth condition of Lemma 31 follows by applying Lemma 15 to U and V.

4.4 Wrap-Up

Theorem 1. [Restated, see original statement.]

The Approximate CT-Matching with Substitutions problem can be solved in 𝒪(nmk2.5) time for k[1,m1/5] and in 𝒪(nk5) time for any k[m1/5,m].

Proof.

We can assume that k<m1/4/128; otherwise, the algorithm of Kim and Han [21], which simply invokes Lemma 24 for k, P, and T[i..i+m) for each i[1,nm+1], runs in 𝒪(nmk)𝒪(nk5) time.

For Δ+ (to be specified later) satisfying kΔm/128, we apply Lemma 26 to P. We either obtain a CT-rainbow of Δ disjoint fragments in P, or a fragment of length at least m/(4Δ) with its minimum CT-block-period p<Δ. This takes 𝒪(mΔ) time.

We then apply the so-called standard trick to reduce the given instance of Approximate CT-Matching with Substitutions to 𝒪(n/m) instances of the same problem with the same pattern P, the same threshold k, and the text being a fragment of T of length at most 3m/2. For i[0,2n/m], define Ti:=T[1+im/2..min{(i+3)m/2,n+1}). It is readily verified that each m-length fragment of T appears in precisely one of the Tis.

We then apply either Lemma 28 or Lemma 35 (depending on the outcome of the analysis of the pattern according to Lemma 26) to solve an instance of Approximate CT-Matching with Substitutions separately for each Ti. In the end, we merge the results.

Each instance is solved in 𝒪(mk4Δ+m2k/Δ) time. The total complexity over all 𝒪(n/m) instances is therefore 𝒪((n/m)(mk4Δ+m2k/Δ))=𝒪(nk4Δ+nmk/Δ). We now distinguish between two cases:

  • If km1/5/1282/5, we balance the two terms in the complexity by setting Δ=m/(128k1.5). Since kΔm/128, and 2kΔ, the time complexity is

    𝒪(nk4mk1.5+nmkm/k1.5)=𝒪(nmk2.5).
  • Else, we have k(m1/5/1282/5,m1/4/128). We set Δ=2k, noting that kΔ=2k2. Since k<m1/4/128, we have k2<m/1282 and hence kΔ=2k2<m/128. Hence, in this case, the time complexity is

    𝒪(nk4(2k)+nmk2k)=𝒪(nk5+nm)=𝒪(nk5).

Since nk5=Θ(nmk2.5) for all k[m1/5/1282/5m1/5], the statement holds.

5 Conclusions and Open Problems

We have presented an efficient algorithm for Approximate CT-Matching with Substitutions. Our algorithm can be seen as a reduction to several instances of computing CHd(XY) for pairs of strings X and Y. We note that any improvement upon the dynamic-programming approach of Kim and Han [21] for this comparison problem would directly yield an improvement over our main result. Interestingly, no (conditional) lower bound is known for either the problem of computing CHd(XY) or Approximate CT-Matching with Substitutions, and devising such a lower bound is another direction for future work. Finally, we hope that our techniques will serve as a foundation for advancing the state of the art in approximate CT-matching under the edit distance.

References

  • [1] Bastien Auvray, Julien David, Samah Ghazawi, Richard Groult, Gad M. Landau, and Thierry Lecroq. Approximate Cartesian tree matching with one difference. CoRR, abs/2505.09236, 2025. doi:10.48550/arXiv.2505.09236.
  • [2] Michael A. Bender, Martin Farach-Colton, Giridhar Pemmasani, Steven Skiena, and Pavel Sumazin. Lowest common ancestors in trees and directed acyclic graphs. J. Algorithms, 57(2):75–94, 2005. doi:10.1016/J.JALGOR.2005.08.001.
  • [3] Dany Breslauer and Zvi Galil. Finding all periods and initial palindromes of a string in parallel. Algorithmica, 14(4):355–366, 1995. doi:10.1007/BF01294132.
  • [4] Karl Bringmann, Marvin Künnemann, and Philip Wellnitz. Few matches or almost periodicity: Faster pattern matching with mismatches in compressed texts. In Proceedings of the Thirtieth Annual ACM-SIAM Symposium on Discrete Algorithms, SODA 2019, pages 1126–1145. SIAM, 2019. doi:10.1137/1.9781611975482.69.
  • [5] Domenico Cantone, Simone Faro, and M. Oguzhan Külekci. The order-preserving pattern matching problem in practice. Discret. Appl. Math., 274:11–25, 2020. doi:10.1016/J.DAM.2018.10.023.
  • [6] 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.
  • [7] Tamanna Chhabra, Simone Faro, M. Oguzhan Külekci, and Jorma Tarhio. Engineering order-preserving pattern matching with SIMD parallelism. Softw. Pract. Exp., 47(5):731–739, 2017. doi:10.1002/SPE.2433.
  • [8] Sukhyeun Cho, Joong Chae Na, Kunsoo Park, and Jeong Seop Sim. A fast algorithm for order-preserving pattern matching. Inf. Process. Lett., 115(2):397–402, 2015. doi:10.1016/J.IPL.2014.10.018.
  • [9] Gianni Decaroli, Travis Gagie, and Giovanni Manzini. A compact index for order-preserving pattern matching. Softw. Pract. Exp., 49(6):1041–1051, 2019. doi:10.1002/SPE.2694.
  • [10] Erik D. Demaine, Gad M. Landau, and Oren Weimann. On Cartesian trees and range minimum queries. Algorithmica, 68(3):610–625, 2014. doi:10.1007/S00453-012-9683-X.
  • [11] Nathan J. Fine and Herbert S. Wilf. Uniqueness theorems for periodic functions. Proceedings of the American Mathematical Society, 16(1):109–114, 1965. doi:10.2307/2034009.
  • [12] Johannes Fischer and Volker Heun. Space-efficient preprocessing schemes for range minimum queries on static arrays. SIAM J. Comput., 40(2):465–492, 2011. doi:10.1137/090779759.
  • [13] Arnab Ganguly, Wing-Kai Hon, Kunihiko Sadakane, Rahul Shah, Sharma V. Thankachan, and Yilin Yang. Space-efficient dictionaries for parameterized and order-preserving pattern matching. In 27th Annual Symposium on Combinatorial Pattern Matching, CPM 2016, pages 2:1–2:12, 2016. doi:10.4230/LIPIcs.CPM.2016.2.
  • [14] Pawel Gawrychowski, Samah Ghazawi, and Gad M. Landau. On indeterminate strings matching. In 31st Annual Symposium on Combinatorial Pattern Matching, CPM 2020, pages 14:1–14:14, 2020. doi:10.4230/LIPIcs.CPM.2020.14.
  • [15] Pawel Gawrychowski and Przemyslaw Uznanski. Order-preserving pattern matching with k mismatches. Theor. Comput. Sci., 638:136–144, 2016. doi:10.1016/J.TCS.2015.08.022.
  • [16] Diptarama Hendrian. Generalized dictionary matching under substring consistent equivalence relations. In WALCOM: Algorithms and Computation - 14th International Conference, WALCOM 2020, pages 120–132, 2020. doi:10.1007/978-3-030-39881-1_11.
  • [17] Davaajav Jargalsaikhan, Diptarama Hendrian, Yohei Ueki, Ryo Yoshinaka, and Ayumi Shinohara. Serial and parallel algorithms for order-preserving pattern matching based on the duel-and-sweep paradigm. Acta Informatica, 61(4):415–444, 2024. doi:10.1007/S00236-024-00464-W.
  • [18] Davaajav Jargalsaikhan, Diptarama Hendrian, Ryo Yoshinaka, and Ayumi Shinohara. Parallel algorithm for pattern matching problems under substring consistent equivalence relations. In 33rd Annual Symposium on Combinatorial Pattern Matching, CPM 2022,, pages 28:1–28:21, 2022. doi:10.4230/LIPIcs.CPM.2022.28.
  • [19] Natsumi Kikuchi, Diptarama Hendrian, Ryo Yoshinaka, and Ayumi Shinohara. Computing covers under substring consistent equivalence relations. In String Processing and Information Retrieval - 27th International Symposium, SPIRE 2020, pages 131–146, 2020. doi:10.1007/978-3-030-59212-7_10.
  • [20] Sung-Hwan Kim and Hwan-Gue Cho. A compact index for Cartesian tree matching. In 32nd Annual Symposium on Combinatorial Pattern Matching, CPM 2021, pages 18:1–18:19, 2021. doi:10.4230/LIPIcs.CPM.2021.18.
  • [21] Sungmin Kim and Yo-Sub Han. Approximate Cartesian tree pattern matching. Theor. Comput. Sci., 1056:115506, 2025. doi:10.1016/J.TCS.2025.115506.
  • [22] Youngho Kim, Munseong Kang, Joong Chae Na, and Jeong Seop Sim. Order-preserving pattern matching with scaling. Inf. Process. Lett., 180:106333, 2023. doi:10.1016/J.IPL.2022.106333.
  • [23] Yoshiaki Matsuoka, Takahiro Aoki, Shunsuke Inenaga, Hideo Bannai, and Masayuki Takeda. Generalized pattern matching and periodicity under substring consistent equivalence relations. Theor. Comput. Sci., 656:225–233, 2016. doi:10.1016/J.TCS.2016.02.017.
  • [24] Takuya Mieno, Mitsuru Funakoshi, Yuto Nakashima, Shunsuke Inenaga, Hideo Bannai, and Masayuki Takeda. Computing maximal palindromes in non-standard matching models. Inf. Comput., 304:105283, 2025. doi:10.1016/J.IC.2025.105283.
  • [25] Temma Nakamura, Shunsuke Inenaga, Hideo Bannai, and Masayuki Takeda. Order preserving pattern matching on trees and dags. In String Processing and Information Retrieval - 24th International Symposium, SPIRE 2017, pages 271–277. Springer, 2017. doi:10.1007/978-3-319-67428-5_23.
  • [26] Akio Nishimoto, Noriki Fujisato, Yuto Nakashima, and Shunsuke Inenaga. Position heaps for Cartesian tree matching on strings and tries. In String Processing and Information Retrieval - 28th International Symposium, SPIRE 2021, pages 241–254, 2021. doi:10.1007/978-3-030-86692-1_20.
  • [27] Tsubasa Oizumi, Takeshi Kai, Takuya Mieno, Shunsuke Inenaga, and Hiroki Arimura. Cartesian tree subsequence matching. In 33rd Annual Symposium on Combinatorial Pattern Matching, CPM 2022, pages 14:1–14:18, 2022. doi:10.4230/LIPIcs.CPM.2022.14.
  • [28] Eric M. Osterkamp and Dominik Köppl. Extending the Burrows-Wheeler transform for Cartesian tree matching and constructing it. In 36th Annual Symposium on Combinatorial Pattern Matching, CPM 2025, pages 26:1–26:17, 2025. doi:10.4230/LIPIcs.CPM.2025.26.
  • [29] Sung Gwan Park, Magsarjav Bataa, Amihood Amir, Gad M. Landau, and Kunsoo Park. Finding patterns and periods in Cartesian tree matching. Theoretical Computer Science, 845:181–197, December 2020. doi:10.1016/J.TCS.2020.09.014.
  • [30] Luís M. S. Russo, Diogo M. Costa, Rui Henriques, Hideo Bannai, and Alexandre P. Francisco. Order-preserving pattern matching indeterminate strings. Inf. Comput., 289(Part):104924, 2022. doi:10.1016/J.IC.2022.104924.
  • [31] Siwoo Song, Geonmo Gu, Cheol Ryu, Simone Faro, Thierry Lecroq, and Kunsoo Park. Fast algorithms for single and multiple pattern Cartesian tree matching. Theor. Comput. Sci., 849:47–63, 2021. doi:10.1016/J.TCS.2020.10.009.
  • [32] Taketo Tsujimoto, Hiroki Shibata, Takuya Mieno, Yuto Nakashima, and Shunsuke Inenaga. Computing longest common subsequence under Cartesian tree matching model. In Combinatorial Algorithms - 35th International Workshop, IWOCA 2024, pages 369–381. Springer, 2024. doi:10.1007/978-3-031-63021-7_28.