Approximate Cartesian Tree Matching
with Substitutions
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 of length and a pattern of length . In the exact Cartesian tree matching problem, the task is to find all length- fragments of whose Cartesian tree coincides with the Cartesian tree 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 that are close to some string whose Cartesian tree matches . In this work, we quantify closeness via the widely used Hamming distance metric. For a given integer parameter , we present an algorithm that computes all fragments of that are at Hamming distance at most from a string whose Cartesian tree matches . Our algorithm runs in time for and in time for , thereby improving upon the state-of-the-art -time algorithm of Kim and Han [TCS 2025] in the regime .
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 matchingFunding:
Jonas Ellert: Partially funded by grant ANR20-CE48-0001 from the French National Research Agency.Copyright and License:
2012 ACM Subject Classification:
Theory of computation Pattern matchingAcknowledgements:
We thank the anonymous reviewers of STACS 2026 for their helpful feedback.Editors:
Meena Mahajan, Florin Manea, Annabelle McIver, and Nguyễn Kim ThắngSeries and Publisher:
Leibniz International Proceedings in Informatics, Schloss Dagstuhl – Leibniz-Zentrum für Informatik
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 of a string is a binary tree defined recursively as follows: the root of the tree corresponds to the index 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 , and the right subtree of the root corresponds to the Cartesian tree of . In what follows, we assume that ties are always resolved in favour of the leftmost elements. The Cartesian tree of a string can be built in linear time [2].
We say that a string CT-matches a string if and only if . This notion of matching is well-behaved: it is a prime example of substring consistent equivalence relations [23] since, if and CT-match, then, for any , and CT-match as well [29].
In the Cartesian tree matching (CT-matching) problem, we are given a text of length and a pattern of length , and the goal is to compute all -length fragments of that CT-match . 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 in , that is, fragments of that are close to a string such that . 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 is provided. Then, we have to report fragments of at distance at most from a string with .
Auvray et al. [1] recently presented an -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 -time algorithm for approximate CT-matching under the edit distance and an -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 and , let denote the minimum number of substitutions needed to transform into a string such that . We further define . We consider the following problem.
Approximate CT-Matching with Substitutions Input: A text of length , a pattern of length , and an integer threshold . Output: for all .
The state of the art solution of Kim and Han [21] computes for each separately in time, resulting in 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 time for and in time for any .
Hence, we improve upon the state of the art by polynomial factors when for any constant . An illustration of the time complexities of our algorithm and the algorithm of Kim and Han [21] for the important case when 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.
Technical overview.
It is a folklore fact that a pattern of length is either periodic or it has at most one exact occurrence in a text of length [3]. In approximate string matching, recent algorithmic breakthroughs [4, 6] were obtained via analogous combinatorial results: either has few approximate occurrences in , or 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 very efficiently for almost all values of when is almost CT-block-periodic. Essentially, we prove (under some extra assumptions) that, for equal-length strings and with , the value of is the same for all choices of .111We use 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 and , thus obtaining short strings and such that , and compute the latter value in 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 , we write to denote . For a set and an integer , we define .
A string of length is a finite sequence of characters over a finite alphabet . For , the -th character of is denoted by , and we use either of , , , and to denote the substring of . If , then is the empty string. We say that a string has an occurrence at position of if and . We may refer to a substring as a fragment if we want to emphasize that we mean the specific occurrence of at position . Two fragments are disjoint if they do not share any positions.
An integer is a period of if for all . The smallest period of is referred to as the period of and is denoted by . A run in is a fragment that satisfies and is inclusion-maximal; that is, (or ) and (or ).
Lemma 2 (Periodicity Lemma (weak version) [11]).
If a string has periods and such that , then is also a period of .
Throughout the paper, we assume that the alphabet is totally ordered, and that an order comparison takes constant time. For a string , we define its leftmost minimum as the (positioned) character , where . In other words, is the leftmost position at which the minimum character in 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 , denoted by , is a rooted ordered binary tree with nodes. The Cartesian tree of an empty string is the order-zero graph. For a non-empty string , is the tree obtained by creating a root node and (recursively) attaching to it as a left subtree and as a right subtree, where is the leftmost minimum of .
Definition 4.
We say that a string CT-matches a string (or that and CT-match) if and only if . We denote that two strings and CT-match by writing and that they do not CT-match by writing .
Fact 5.
The CT-equivalence relation () is a transitive relation. That is, for any three strings , , and , if and , then as well.
For strings (the text) and (the pattern), we say that is a CT-occurrence of in (or that CT-occurs in at position ) if . The CT-matching problem consists in computing all CT-occurrences of in .
Lemma 6 ([29]).
Given a text and a pattern , all CT-occurrences of in can be computed in time.
Lemma 7 ([29]).
Given a text and patterns , all the CT-occurrences of all the patterns in can be computed in time.
For equal-length strings and , denotes the minimum number of substitutions needed to transform into a string such that . We further define . Given a text and a pattern , we say that has a -approximate CT-occurrence at a position of if .
The following fact states that CT-matching is a substring consistent equivalence relation.
Fact 8 (Theorem 2, [29]).
For any strings and with , we have for all .
There is a natural bijection between positions of a string and nodes in . We formalise this concept using the previous-smaller-or-equal-value function. For a string , we define
The parent-distance representation of a string (see [29]) is a length- string with
Intuitively, we have if and only if the left subtree of the node corresponding to in is . Given either of and , one can (recursively) construct , and hence the following lemma holds.
Lemma 9 ([29, Theorem 1]).
For equal-length strings and , if and only if , or equivalently .
We provide an example of a Cartesian tree , the function , the array , and the distance function CHd in Figure 2.
For a string , analogously to , we define the next-smaller-value function, which captures the structure of the Cartesian tree as well:
We also define a length- string by
An analogue of Lemma 9 for and 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 has a CT-border-period if and only if .
Lemma 11.
The leftmost minimum of a string with CT-border-period lies outside .
Proof.
Assume that is the position of the leftmost minimum of . Then is also the leftmost minimum of both and , and hence it is the root of both and . However, in this case, the left subtree under the root of is of size , while the the left subtree under the root of is of size . This contradicts the assumption that .
Definition 12.
A string has a CT-block-period if and only if
-
divides ,
-
is a CT-border-period of , and
-
the leftmost minimum of is either or .
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 of a string , either for all or for all , thus providing locality guarantees.
Lemma 14.
Given and a positive integer that is a CT-border-period of , we can compute a fragment of length at least that has CT-block-period in time.
Proof.
Fact 8 implies that any substring of of length at least has CT-border-period . Let and note that . By Lemma 11, there exists an offset such that the leftmost minimum of is either or . If the leftmost minimum is , then the fragment has CT-block-period . Otherwise, the fragment has CT-block-period .
Lemma 15.
Consider a string that has a CT-block-period and such that is the leftmost minimum of . For , let . For all , is the leftmost minimum of .
Proof.
For denote . We prove by induction the more general statement that is a CT-block-period of for all with being the leftmost minimum of . The induction hypothesis holds for since is the leftmost minimum of and is therefore smaller than (since ), where is the leftmost minimum of . Now, consider any and suppose that is a CT-block-period of with being the leftmost minimum of . First, since is a CT-block-period of , we have and hence the leftmost minimum of is . Further, Fact 8 implies that
and hence is a CT-border-period of . Finally, since divides , it also divides . This completes the induction and the statement follows.
An analogue of Lemma 15 for the case when is the leftmost minimum of is given in the full version.
Fact 16.
Consider a string . The parent-distance representation of a fragment of is given by, for ,
If is a leftmost minimum of , then is a suffix of .
Lemma 17.
Consider a string and a fragment with leftmost minimum . Then, is a CT-block-period of if and only if is a period of and divides .
Proof.
- (:)
- (:)
-
We first argue that it suffices to show that is the leftmost minimum of . If this is indeed the case, we have that is a suffix of which, together with the fact that , implies that and hence that by Lemma 9. Since divides and is the leftmost minimum of , is a CT-block-period of .
Now, suppose for the sake of contradiction, that the leftmost minimum of is at some position . Then, . Since is the leftmost minimum of , . Since is periodic with period , we have . Therefore, our assumption implies that , which contradicts the assumption that is the leftmost minimum of .
An analogue of the above lemma for the case when the leftmost minimum of is is given in the full version.
Corollary 18.
For equal-length strings and that have a common CT-block-period , we have if and only if .
Proof.
- (:)
-
This implication follows directly from Fact 8.
- (:)
-
Due to Lemma 15 and its analogue, both and have their leftmost minima at the same position (since and 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 , Lemma 9 yields that . Further, we have and by Fact 16. Hence, . Since is a CT-block-period of each of and , by applying Lemma 17 to each of and , we conclude that is a period of both and . This directly implies that , and we hence have by Lemma 9.
Lemma 19.
Suppose that a fragment has minimum CT-block-period . Then, for any such that , , and , we have that and that has minimum CT-block-period .
Proof.
Without loss of generality, assume that is the leftmost minimum of . The complementary case when is the leftmost minimum can be handled in a symmetric manner using the analogues of the lemmas used below.
Fix satisfying the conditions of the claim. If , then the CT-border-period of implies that
Now, observe that is the leftmost minimum of by Lemma 15. Additionally, we have by Fact 8 because is a CT-border-period of . Finally, divides by our assumptions and hence is a CT-block-period of .
It remains to show that is the minimum CT-block-period of . Towards a contradiction suppose that has minimum CT-block-period . Then, by Lemma 17, has a period and has a period . Since the length of the fragment is , an application of the Periodicity Lemma (Lemma 2) yields that has period . Consequently, also has period . Another application of Lemma 17 implies that has CT-block-period (since divides the length ), a contradiction.
Definition 20.
Let be a string. A fragment with minimum CT-block-period is called a CT-run if and only if is not a CT-block-period of (or ) and is not a CT-block-period of (or ).
The occurrences of a periodic pattern in a text form arithmetic progressions with each such progression corresponding to a run with period . We show an analogous result for CT-occurrences.
Example 21.
Consider a pattern . is of length and has a CT-block-period . The leftmost minimum of is at its first position. The parent-distance array for is .
Consider the text of length . The parent-distance array for is: .
There are two CT-occurrences of in :
-
at position , , where ;
-
at position , , where .
Note that the fragment forms a CT-run in with minimum CT-block-period .
Lemma 22.
Let be a pattern of length with minimum CT-block-period , and let be a text of length . The exact CT-occurrences of in can be partitioned into maximal arithmetic progressions with common difference . For each such progression , the fragment is a CT-run with minimum CT-block-period . For any two such arithmetic progressions and , the two runs and overlap by fewer than positions.
Proof.
We henceforth assume that the leftmost minimum of is at its first position. The proof for the complementary case, that is, when the leftmost minimum of is , is symmetric (using ND instead of PD and the analogous versions of the used lemmas).
Let . By the CT-block-periodicity of and Lemma 17 we have . Since is the leftmost minimum of , Fact 16 and 9 imply that CT-occurs at some position in if and only if the following two conditions hold:
-
PD-match condition: ;
-
left-min condition: is the leftmost minimum of .
Claim 23.
Consider a maximal arithmetic progression of occurrences of in . For , denote . Then, either does not have any CT-occurrence at a position of in , or there exists an integer such that both of the following hold:
-
the intersection of the set of CT-occurrences of in and is ;
-
is a CT-run with minimum CT-block-period .
Proof.
By the definition of , we have for all . Hence, the PD-match condition holds for all . If the left-min condition fails for every element of , then does not have any CT-occurrence at any position of in , and the claim follows. Otherwise, let . We show by induction that the left-min condition holds for all . The base case holds by definition. Assume that it holds for some . An application of Lemma 15 to implies that is the leftmost minimum of . This completes the proof of the inductive step and hence concludes the proof of the first item. Let . By repeatedly applying Lemma 15, we conclude that the leftmost minimum of is , and hence that is a CT-block-period of . If had a smaller CT-block-period, then, by Lemma 19, the same would hold for , contradicting the assumption that has minimum CT-block-period . Finally, we cannot prepend or append characters to while maintaining that it has CT-block-period : either the obtained string does not have its leftmost minimum at its first position or we contradict the maximality of . 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 in at position implies an occurrence of in at position , noting that the occurrences of in can be partitioned into maximal arithmetic progressions with period such that any two elements from distinct arithmetic progressions differ by more than (see [3, 11]).
4 Approximate CT-Matching with Substitutions
Kim and Han [21] recently presented a dynamic programming algorithm that, given two strings and , computes the minimum cost of a sequence of edit operations (insertions, deletions, and substitutions) required to transform into a string such that . 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 and , and an integer threshold , we can compute in 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 such that .
Lemma 26.
Let with . Given and a string , in time, we can either compute a set of disjoint fragments of , each of length , that form a CT-rainbow or report a fragment of length at least that has a CT-block-period less than , together with its minimal CT-block-period.
Proof.
Let . We process in a left-to-right manner, attempting to identify -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 in time using Lemma 6. For each inserted fragment, we use a unique symbol for marking.
We first insert fragment into . Let 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 such that does not CT-match any element of . To do this, it suffices to find, in time, the first unmarked position in , if one exists. If we can always find such a position 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 since the length of the gap between any two consecutive fragments is less than and . Inserting a fragment into and marking all of its exact CT-occurrences takes time. In the case when we can always find a fragment to insert into , the algorithm thus runs in time.
Now consider the complementary case when, after inserting some fragment into , we have and all positions in are marked. Then, by the pigeonhole principle, some fragment in has two CT-occurrences at positions in with . We find two such positions (marked with the same symbol) naively in time. Let . has length and CT-border-period . We apply Lemma 14 to trim . Both conditions of the lemma are satisfied since , , and , and hence
Trimming yields a fragment with CT-block-period and length
Finally, we naively compute the smallest CT-block-period of by checking each integer in in time, for a total running time of , and return the pair .
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 at a position in contributes a mark to position , indicating a potential starting position of a -approximate CT-occurrence of in . The following simple fact captures the key property we use: if , then position must receive at least marks.
Lemma 27.
Let with . Consider strings satisfying . Let be a set of disjoint fragments of . Then there exists a set of size at least such that for all .
Proof.
Let be a string obtained from by substituting at most characters such that . Let . Set is of size at least as the substitutions transforming into affect at most fragments . For each , Fact 8 implies that . Moreover, for each , we have 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 with and . Given , a text , and a pattern , together with a CT-rainbow consisting of disjoint fragments of , each of length , we can compute for all in time.
Proof.
We perform multiple-pattern CT-matching in for all fragments of in time using Lemma 7. If a fragment CT-matches a fragment , we add a mark at position of . By the fact that is a CT-rainbow and transitivity (Fact 5), at most one fragment of can CT-match at any position of . Hence, the total number of marks is . Furthermore, Lemma 27 implies that if , then position must receive at least marks. There are such positions, which can be identified at no additional cost during the marking process. Each of these positions is then verified in time using Lemma 24, yielding a total verification time of .
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 and under certain conditions before applying Lemma 24. Intuitively, whenever a long CT-block-periodic fragment of is aligned with a corresponding periodic fragment of , 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.
Lemma 29.
Consider and strings and such that all of the following hold:
-
, , and , where ;
-
;
-
there is no position such that ;
-
if we define , then is a minimum in , and is a minimum in ;
-
.
Any sequence of substitutions that transforms into with does not perform any substitution in fragment .
Proof.
Consider any sequence of substitutions that transforms into such that . We fix to be the minimal and maximal values, respectively, such that and are not modified. (There are at least two distinct values because .) We show that no substitution is performed in .
Let . We claim that . If not, there would exist with . We show that such does not exist by distinguishing between the following four cases:
- Case 1:
- Case 2:
-
. is minimal in by assumptions. Hence, . We obtain due to Lemma 9 and the observation that:
- Case 3:
-
. Since is minimal in , we have . Therefore, follows from .
- Case 4:
We have shown that . Hence, the considered sequence of substitutions did not modify . Finally, by the definition of and , the characters in positions and in must have been modified. We therefore have , which implies and . Consequently, there are no substitutions in .
Lemma 30.
Consider strings and with . Let such that and is minimal in . Then .
Proof.
The assumption that , together with Fact 8 and 9, imply that is minimal in . For , let . It is easy to see that the following hold:
-
For , . (This is trivial.)
-
For with , we have .
-
For with , we have .
-
For with , we have .
Note that the definition of depends only on the array. Since , we have that by Lemma 9. Therefore, it follows that . By applying Lemma 9 again, we conclude that .
Lemma 31.
Consider and strings and such that all of the following hold:
-
, , and , where ;
-
;
-
there is no position such that ;
-
if we define , then is a minimum in , and is a minimum in .
Then , where
Proof.
It suffices to prove the following two claims, which together imply the statement.
Claim 32.
implies .
Claim 33.
implies .
Proof of Claim 32.
Assume that and consider any sequence of substitutions that transform into a string with . By Lemma 29, we have . Note that we can perform the same sequence of substitutions (with an appropriate shift) on as well. Hence, there is a sequence of substitutions that transforms into
It remains to be shown that , which implies . Note that and can be obtained by deleting fragments and from and , respectively. By the definition of , we know that is a minimum in . Hence, we can apply Lemma 30 to and with and , thus obtaining .
Proof of Claim 33.
Assume that and consider any sequence of substitutions that transform into a string with . It can be readily verified that the strings and still satisfy the conditions of Lemma 29 with parameter . Therefore, we have:
We observe that the same sequence of substitutions can also be applied directly to , resulting in the string: .
It remains to be shown that , which implies . Note that and , as well as and , share a prefix of length . Due to , combined with Fact 8 and 9, it is clear that, for every , .
Next, we observe that . Recall that and are minimal in and , respectively. Due to , combined with Fact 8 and 9, we have .
Finally, we consider . Let . We observe that and , as well as and , share a suffix of length . If , then already implies . It remains to consider the case when and . In this case, since is minimal in , it holds that , and, by the condition of the lemma, . Note that , as we obtained by merely deleting some elements between and . Due to , we have . Finally, we obtain from by inserting into values that are at least as large as between positions and . Since , we know that , and thus all inserted values are at least . Thus, , as required.
The combination of the two claims yields that either both and are at most and are in fact equal, or they are both greater than .
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 and strings and such that all of the following hold:
-
, , and , where ;
-
;
-
there is no position such that ;
-
if we define , then is a minimum in , and is a minimum in .
Then , where
We are now ready to prove the main algorithmic result of this section.
Lemma 35.
Let satisfy , , , and . Given , , , a text , a pattern , and a fragment of length at least with minimum CT-block-period , we can compute for all in time.
Proof.
Due to , the fragment is of length at least and hence consists of at least blocks of length ; namely, for . In any -approximate CT-occurrence of in , at least of those blocks are aligned with fragments of that CT-match them. These blocks are partitioned into at most sets of contiguous blocks by the at most blocks that are aligned with fragments of that do not CT-match them. Hence, in any -approximate CT-occurrence of in , there exists a fragment of that consists of at least blocks and is CT-matched exactly.222Note that it might be a different fragment for each -approximate CT-occurrence of in . We have . Further, the CT-block-periodicity of implies that and, combined with Lemma 19, that has minimum CT-block-period .
For a string , a block of length with , is bad if and good otherwise. Intuitively, if we have many bad blocks in , 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 -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 and one in ) that are composed solely of good blocks using either Lemma 31 or Lemma 34 before invoking Lemma 24.
We compute a fragment of by extending blockwise to the left (and to the right) by prepending (resp. appending) blocks of characters until we either accumulate bad blocks in that direction or there are fewer than characters left in that direction – in the latter case, we almost reach the beginning (resp. end) of .
Case I: Enough blocks accumulated in at least one direction.
Assume, without loss of generality, that we accumulated bad blocks while extending to the left.
We employ the linear-time exact CT-matching algorithm of Lemma 6 to compute all exact CT-occurrences of in . By Lemma 22, these CT-occurrences can be partitioned into arithmetic progressions with common difference such that the CT-occurrences in each of the progressions span a CT-run of length with minimum CT-block-period . Let denote the set of CT-runs in that are spanned by the exact CT-occurrences of .
Let us fix a CT-run . We extend to the left using a procedure identical to the one performed on until we either accumulate bad blocks or the fragment contains . Consider aligning the pattern with a fragment such that a fragment of that CT-matches is aligned with a fragment of that CT-matches it. By Lemma 22, any such alignment satisfies , that is, it perfectly aligns the block boundaries of and . 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 into a string . Thus, substitutions performed on can fix at most 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 bad blocks of must be aligned with one of the at most bad blocks in the extension of . There are only ways to align such a pair of bad blocks, each yielding a candidate starting position of a -approximate CT-occurrence of in . The described procedure can be implemented naively in time.
We perform this procedure for all CT-runs in , thus obtaining candidate starting positions. We then invoke Lemma 24 for each such position. In total, this takes time .
Case II: The pattern is almost CT-block-periodic.
In the complementary case, we did not accumulate bad blocks in either direction. Thus, where and consists of -length blocks, at most of which are bad.
Claim 36.
In time, we can either decide that has no -approximate CT occurrences in or compute a fragment such that the following hold:
-
for all , , implies that and .
-
and ,
Moreover, is partitioned into -length blocks of which are explicitly marked as bad.
Proof.
By Lemma 19, the fragment has minimum CT-block-period . Thus, by Lemma 22, any two exact CT-occurrences of in are at distance at least and there are at most CT-occurrences in total.
Now, any -approximate CT-occurrence of in implies a large number of exact CT-occurrences of at positions that are in a single equivalence class modulo , with each such CT-occurrence corresponding to aligning a good block of with a fragment of . Specifically, by accounting for the at most substitutions (each potentially affecting three good blocks), the at most bad blocks in , as well as and which are of total length at most , we conclude that we must have at least such exact CT-occurrences. The inequalities and imply that , and hence . Since we have a total of CT-occurrences of in and , there is at most one residue modulo , say , with at least CT-occurrences of starting at a positions equivalent to modulo .
We compute all exact CT-occurrences of in in time using Lemma 6 and identify the majority residue modulo , say , resolving ties arbitrarily. If the CT-occurrences of at positions of equivalent to modulo are fewer than , we conclude that does not have any -approximate CT-occurrences in and terminate the algorithm. We henceforth, assume that we are in the complementary case.
We select as the leftmost position in such that and . We extend the fragment in each direction until we either accumulate bad blocks or there are fewer than characters left. Let denote the obtained fragment.
Any -approximate CT-occurrence of in must align with a fragment of the form for nonnegative integers and . Further, in this CT-occurrence, must be aligned with a fragment of that contains . Now, observe that at most bad blocks of can be contained in , as at most of them can be aligned with CT-matching bad blocks of and the at most substitutions may fix at most pairs of bad blocks in with good blocks in . This implies that .
Next, we define the boundaries and , and describe the decomposition . Let be the smallest positive integer in , let be the largest integer in , and set . Since, for any approximate CT-occurrence we have , this ensures that . Further we have that since . The partition of is then defined as: , , . Finally, we return , , and the bad blocks in .
We also designate each block in as implicitly bad if it contains a position such that there exists a position in either an explicitly bad block or in , such that or . Note that the number of implicitly bad blocks is (since ) as each (explicitly) bad block implies implicitly bad ones and implies 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 such that or for some position , then the values or 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 for each of the positions in that satisfy and . Let . inherits its block-decomposition from , as well as the classification of some blocks as bad. We call the considered position an overlap position if there exist positions in and in that belong to (implicitly or explicitly) bad blocks and satisfy , and a non-overlap position otherwise. We treat overlap and non-overlap positions differently:
-
If is an overlap position, we employ Lemma 24 to compute in time. The number of overlap positions is since we require one of the (implicitly or explicitly) bad blocks in to be within blocks of one of the bad blocks in . The total time required for overlap positions is thus . Note that we can efficiently enumerate all the overlap positions using the list of bad blocks for both and .
-
If is a non-overlap position, then we can show that only depends on the parts of the alignment of and in the -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 and 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 is the leftmost minimum of and Lemma 34 otherwise, that is, if the leftmost minimum is . Conceptually, we perform the following procedure. We traverse the lists of bad blocks in each of and from left to right in parallel in time. Whenever we encounter a maximal pair of fragments and of length at least that only consist of blocks that are not (implicitly or explicitly) bad, we replace with and with . A repeated application of either Lemma 31 or Lemma 34 guarantees that , where and are the strings obtained from and , respectively. Instead of making the replacements on and , we explicitly construct and by copying the fragments of and that are not deleted by the conceptual procedure described above.
As we have (implicitly or explicitly) bad blocks in and bad blocks in , and since each bad block prevents blocks from being trimmed, we have . The computation of using Lemma 24 thus takes time and returns . Over all non-overlap positions, the total time required is .
It remains to be shown that the described applications of Lemma 31 are valid if is the leftmost minimum of ; applications of Lemma 34 are valid in the remaining case by symmetric arguments. First, note that is a CT-block-period of and 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 .
-
–
The second condition of Lemma 31 holds by Corollary 18 as is a CT-block-period of both and , and .
- –
- –
-
–
4.4 Wrap-Up
Theorem 1. [Restated, see original statement.]
The Approximate CT-Matching with Substitutions problem can be solved in time for and in time for any .
Proof.
We can assume that ; otherwise, the algorithm of Kim and Han [21], which simply invokes Lemma 24 for , , and for each , runs in time.
For (to be specified later) satisfying , we apply Lemma 26 to . We either obtain a CT-rainbow of disjoint fragments in , or a fragment of length at least with its minimum CT-block-period . This takes time.
We then apply the so-called standard trick to reduce the given instance of Approximate CT-Matching with Substitutions to instances of the same problem with the same pattern , the same threshold , and the text being a fragment of of length at most . For , define . It is readily verified that each -length fragment of appears in precisely one of the s.
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 . In the end, we merge the results.
Each instance is solved in time. The total complexity over all instances is therefore . We now distinguish between two cases:
-
If , we balance the two terms in the complexity by setting . Since , and , the time complexity is
-
Else, we have . We set , noting that . Since , we have and hence . Hence, in this case, the time complexity is
Since for all , 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 for pairs of strings and . 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 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.
