On the Complexity of the Matching Problem of Regular Expressions with Backreferences
The project
Showcase
Soh Kumabe and Yuya Uezato
ICALP 2026 (LIPIcs, vol. 374)DOI 10.4230/LIPIcs.ICALP.2026.135Theoretical computer science: Algorithms, complexity and games
- article
- nicematrix
- extpfeil
- forest
- bclogo
Compare with TeX's PDFOriginalSource
CC BY 4.0, published at drops.dagstuhl.de. “On the Complexity of the Matching Problem of Regular Expressions with Backreferences” by Soh Kumabe, Yuya Uezato, arXiv:2605.07289v1 (published in ICALP 2026, LIPIcs vol. 374, 10.4230/LIPIcs.ICALP.2026.135). Licensed under CC BY 4.0. Typeset here by reflowtex from the authors' source.
On the Complexity of the Matching Problem of
Regular Expressions with Backreferences∗
Soh Kumabe†1 and Yuya Uezato‡1,2
1CyberAgent, Inc., Japan.
2National Institute of Informatics, Japan.
Abstract
Regular Expression Denial of Service (ReDoS) is a well-known type of algorithmic complexity attack, where an adversary supplies maliciously crafted strings to a regular expression matching engine, aiming to exhaust computational resources of systems. Even quadratic-time behavior in matching engines has been exploited in successful attacks, as exemplified by major outages at Stack Overflow (2016) and Cloudflare (2019). These incidents motivate a fundamental question: Is it possible to construct matching engines that are provably efficient, running in linear or near-linear time in the length of the input string?
For classical regular expressions (REGEX), Thompson’s construction yields a linear-time algorithm for fixed expressions. However, practical engines support powerful features such as backreferences, which allow capturing a substring and reusing it later. This feature strictly extends the expressive power of REGEX but unfortunately increases the risk of ReDoS attacks.
This paper investigates the fine-grained complexity of the string matching problem for regular expressions with backreferences (REWBs). Specifically, we consider r-use k-REWBs, i.e., REWBs with k variables such that, in any computation, the total number of backreference executions is at most r.
On the hardness side, we show that the string matching problem for k-REWBs cannot be solved in O(n2k−ϵ) time for any ϵ > 0 under the Strong Exponential Time Hypothesis (SETH), where n is the length of the input string. We also prove that this problem is W[2]-hard when parameterized by the length of the REWB expression, strengthening the previous W[1]-hardness result. Moreover, we prove that this problem for 2-use 2-REWBs cannot be solved in n1+o(1) time unless the triangle detection problem can be solved in that time.
On the algorithmic side, we present an O(n log2 n)-time algorithm for 1-use REWBs. In particular, we focus on the ABCBD problem, which is the REWB matching problem for the form A (B)x C \x D where A, B, C, and D are fixed REGEXes. We also show that every 1-use REWB can be transformed into this canonical form. Our algorithm significantly improves upon the recent O(n2)-time algorithm for the ABCBD problem by Nogami and Terauchi (MFCS, 2025). Our algorithm is highly non-trivial and employs several techniques including suffix trees, transition monoids of REGEXes, factorization forest data structures, and periodicity of strings.
1 Introduction
Background. Regular expressions are widely used in web services to validate and filter user-provided text. However, depending on the engine implementation and the specific expressions used, the worst-case regular expression matching time can be prohibitive. In most web-service settings, expressions are fixed by the application, while the input string is provided by potentially untrusted users. In such cases, an adversary can craft inputs that trigger the worst-case behavior, potentially exhausting computational resources (CPU and memory) and causing service outages.
Attacks that exploit such worst-case algorithmic behavior are known as algorithmic complexity attacks [31]. Those specifically involving regular expressions are called ReDoS (Regular Expression Denial of Service) [30]. ReDoS is a major vulnerability and is cataloged in the Common Weakness Enumeration (CWE, the de facto standard for vulnerability classification) as CWE-1333 [75].
We highlight two well-documented service outages caused by ReDoS, together with the real-world regular-expression that triggered the worst-case behavior in the deployed engines.1
1These two examples are written in the syntax of the corresponding real-world regex engines, not in the formal syntax introduced below. For example, \s is a whitespace character class and \u200c is the Unicode escape for U+200C. These examples are used only to demonstrate that backtracking engines can already cause quadratic-time ReDoS without backreferences.
1. The 2016 Stack Overflow outage, caused by the expression ^[\s\u200c]+|[\s\u200c]+$ [101].
2. The 2019 Cloudflare outage, caused by an expression whose core part is .*.*=.* [57].
According to their reports [101, 57], these outages occurred because the employed regular expression engines relied on backtracking algorithms. Consequently, the above expressions exhibited quadratic-time computation on crafted inputs.2 It is well known that backtracking-based engines can cause catastrophic exponential backtracking [48, 25, 53], and it is widely believed that avoiding exponential behavior would be sufficient. However, these incidents were surprising in showing that even quadratic-time behavior can lead to a system outage. This is stated explicitly in the post-mortem [101], which we quote verbatim below:
2Readers can reproduce the quadratic-time behavior of these expressions using the online demos in [9, 8].
So the Regex engine has to perform a “character belongs to a certain character class” check (plus some additional things) 20,000+19,999+19,998+…+3+2+1 = 199,990,000 [sic] times, and that takes a while. This is not classic catastrophic backtracking (performance is O(n2), not exponential, in length), but it was enough.
Motivated by this background, we propose the following criterion:
A regular expression engine is ReDoS-safe if, for each fixed expression, it runs in linear or near-linear time in the length of the input string.
In this paper, we address the following fundamental questions: Can we construct a ReDoS-safe regular expression engine in the above sense? If so, which practical extensions can such an engine still support?
Complexity of Regex matching problems. The term “regular expression” is used for several different formalisms. In this paper, following classical formal language theory, we use the standard (Kleene) regular expressions, denoted by Regex.
Definition 1 (Syntax of Regex). The syntax of Regex over an alphabet Σ is given by the grammar:
E ::= ∅ | ϵ | σ | E + E | E · E | E∗ where σ ∈ Σ.
We give the formal semantics, including the language L (·), in Section 2. For Regex, we consider the following computational problem.
Regex Matching Problem Fixed Object: A Regex E. Input: A string w. Task: Deciding if w ∈ L (E) where L (E) is the language of E.
Is it possible to design a ReDoS-safe engine for the Regex matching problem? The answer is Yes. Using Thompson’s construction [103] and the standard efficient NFA simulation [25][4, Sec 3.7], we can solve this problem in O(|E| |w|) time, which is linear in |w| for each fixed E.
From Regex to REWB. Does the linear-time algorithm for Regex matching fully resolve ReDoS in practice? The answer is No. This is because most real-world regular expression engines support extensions beyond Regex. One of the most prominent extensions is backreferences. We use REWB to denote the class of regular expressions with backreferences. Unlike Regex, REWB allows variables that capture substrings matched by a subexpression and refer back to that captured string later. Backreferences are widely supported in the standard regular expression libraries of major programming languages (e.g., C++, Java, JavaScript, Python, Ruby, Perl, PHP, and OCaml). The syntax of REWB is given as follows.
Definition 2 (Syntax of REWB). The syntax of REWB is given by the following grammar:
E ::= ∅ | ϵ | σ | E + E | E · E | E∗ | (E)x | \x,
where σ ∈ Σ and x is a variable. The expression (E)x captures the substring matched by E and stores it in x, while \x refers to the content stored in x.
As with Regex, we give the formal semantics of REWB in Section 2.
We note that REWB is strictly more expressive than Regex. Consider the expression E := ((0 + 1)∗)x \x. Intuitively, the subexpression ((0 + 1)∗)x matches an arbitrary string w ∈ {0, 1}∗ and binds it to x. Then, \x matches the captured substring stored in x. Hence, E defines the non-regular language {ww : w ∈ {0, 1}∗}.
This paper focuses on the following problem.
REWB Matching Problem Fixed Object: A REWB E. Input: A string w. Task: Deciding if w ∈ L (E).
This raises a natural question: Is it possible to design a ReDoS-safe engine for the REWB matching problem? Unfortunately, No. If we view E as part of the input and parameterize the problem by c, the number of variable occurrences in E, then the REWB matching problem is W[1]-hard [102, 43]. In particular, under the standard assumption FPT = W[1], there is no uniform algorithm running in f(c) · |w|O(1) for all inputs (w, E). However, this worst-case hardness is too pessimistic for practice. In practice, many real-world REWB expressions use backreferences in restricted ways. To identify which REWB subclasses are ReDoS-safe and which remain vulnerable, we need a fine-grained analysis of the REWB matching problem.
Classification of REWB. We write k-REWB to denote the set of REWBs that have at most k distinct variables. We say that an expression E is r-use if, for every input string w and for all computations of E on w, the total number of executed backreferences (i.e., executed occurrences of \x) is at most r. Intuitively, a computation is one possible run of E on w; different runs may arise from different choices at the union and Kleene-star subexpressions of E, and may therefore execute different numbers of backreferences. If no such finite r exists, we call E ω-use. We illustrate these notions with the following examples:
• (Σ∗)x\x is a 1-use 1-REWB because there is only one variable x, which is referenced once.
• (Σ∗)x \x \x is a 2-use 1-REWB because there is only one variable x, which is referenced twice.
• (Σ∗)x \x (Σ∗)x \x is also a 2-use 1-REWB that reuses the single variable x.
• (Σ∗)x (\x)∗ is an ω-use 1-REWB, as x can be referenced an unbounded number of times.
• (Σ∗)x (Σ∗)y\y\x is a 2-use 2-REWB because it contains two variables x and y, which are referenced a total of two times.
We allow both capture groups and backreferences to appear inside capture groups. That is, the body of a capture group (· · · )x may contain subexpressions of the form \y or (· · · )y, where y may be equal to x. For example, (\x \x)x (“doubling the content of x”) and (0 \x 0)x (“wrapping x with 0s”) are well-formed.
Known algorithmic results for REWB matching. The current best-known algorithm for k-REWB matching runs in O(|E| · |w|1+2k) time [35, §IX. C][88] based on standard dynamic programming. Recently, Nogami and Terauchi studied the ABCBD problem, a subclass of the 1-REWB matching problem, and gave an O(|E|2|w|2)-time algorithm [88, Thm. 5]. Although their result improved upon the standard DP-based O(|E| |w|3)-time algorithm, it is not ReDoS-safe due to its quadratic dependence on |w|.
1.1 Our Contribution
We summarize our main hardness and algorithmic results.
1.1.1 Hardness Results for the REWB Matching Problem
We strengthen the previously known W[1]-hardness results [102, 43] by showing W[2]-hardness.
Theorem 3. When the expression E is part of the input, the REWB matching problem is W[2]-hard parameterized by the expression size |E|.
Assuming that Triangle Detection on an m-edge graph does not admit an m1+δ−o(1)-time algorithm [1, Conjecture 3], we derive a conditional lower bound even for the highly restricted class, 2-use 2-REWB.
Theorem 4. Assuming the no-almost-linear-time hypothesis for Triangle Detection, there exists a fixed 2-use 2-REWB expression Ψ such that the matching problem for Ψ cannot be solved in |w|1+δ−o(1) time for some constant δ > 0.
Under the k-Orthogonal Vectors hypothesis (k-OV) [107], which is a weaker assumption than the strong exponential time hypothesis (SETH), we have the following result.
Theorem 5. Assuming the k-OV hypothesis, for each fixed integer k ≥ 1, there exists a fixed ω-use k-REWB expression Ψk such that the matching problem for Ψk cannot be solved in O(|w|2k−ϵ) time for any ϵ > 0.
Very recently and independently of our work, Nogami and Terauchi [89, Theorem 1] proved the following lower bound: assuming the 2-OV hypothesis, no algorithm solves the 1-REWB matching problem in O(|w|2−ϵ poly(|E|)) time. Our result strengthens theirs in the following two ways: (1) our hardness holds for general k; and (2) as our hardness holds for a fixed expression Ψk, it rules out any speedup gained by allowing arbitrary dependence on |E|.
1.1.2 Algorithmic Results
We have shown that the REWB matching problem remains hard even for 2-use 2-REWBs (Theorem 4) and for (ω-use) 1-REWBs (Theorem 5 with k = 1) when seeking a near-linear-time algorithm. This naturally raises the question: What is the complexity of 1-use 1-REWB matching? Our main algorithmic result is a near-linear time algorithm for the following special case:
ABCBD Problem Fixed Objects: Regexes A, B, C, and D. Input: A string w. Task: Deciding if we can decompose w into w = wA wB wC wB wD so that wA ∈ L (A), wB ∈ L (B), wC ∈ L (C), and wD ∈ L (D). Equivalently, decide whether w ∈ L (A (B)x C \x D).
At first glance, this syntax may appear highly restricted. However, the ABCBD problem captures the general case of 1-use REWB in the following sense:
Theorem 6. For any 1-use REWB E, there exists an equivalent REWB of the following form:
(A1 (B1)x C1 \x D1) + (A2 (B2)x C2 \x D2) + · · · + (AK (BK)x CK\x DK) + E′
where Ai, Bi, Ci, Di, E′ are Regexes. We can construct the above representation in O(|E|4) time. Furthermore, the following holds for their size:
K = O(|E|2), |Ai| = O(|E|2), |Bi| = O(|E|), |Ci| = O(|E|2), |Di| = O(|E|), |E′| = O(|E|2).
The main result of this paper is as follows.
Theorem 7. The ABCBD problem admits an O(|w| log2 |w|)-time algorithm. The hidden constant is 2O((|A|+|B|+|C|+|D|)2).
This significantly improves the O(|w|2)-time algorithm of Nogami and Terauchi [88]. Our algorithm is highly nontrivial; for a more detailed overview, see Section 1.3. Note that our algorithm can also be viewed as a near-linear-time fixed-parameter algorithm for the ABCBD matching problem, parameterized by the (combined) size of Regexes A, B, C, and D. Combining Theorems 6 and 7, we obtain the following.
Theorem 8. The 1-use REWB matching problem admits an O(|w| log2 |w|)-time algorithm. The hidden constant is 2O( |E|4 ).
Note that the hidden constant 2O( |E|4 ) is larger than in Theorem 7 because Theorem 6 may yield expressions of quadratic length.
Remark: Uniformity The algorithms in Theorems 7 and 8 are uniform. Namely, they take the relevant expressions (A, B, C, D in Theorem 7, and E in Theorem 8) together with the input string w, perform all preprocessing depending on these expressions, and then run the main procedures. The fixed-object formulation only emphasizes the dependence on |w|; no non-uniform advice depending on the fixed expressions is assumed.
As a key subroutine for solving the ABCBD problem, we have also developed an efficient algorithm for the following problem.
XYαZ Problem Fixed Objects: An integer α ≥ 2 and Regexes X, Y, and Z. Input: A string w. Task: Deciding if we can decompose w into w = wX α times wY · · · wY wZ so that wX ∈ L (X), wY ∈ L (Y), and wZ ∈ L (Z). Equivalently, decide whether w ∈ L X (Y)x (\x)α−1 Z.
Our theorem for this problem is the following.
Theorem 9. The XYαZ problem admits an O(|w| log |w|)-time algorithm. The hidden constant is 2O(s2) + α · 2O(s), where s := |X| + |Y| + |Z|. Alternatively, at the cost of an additional log |w| factor (i.e., time O(|w| log2 |w|)), we can achieve a polynomial dependence on s + α.
1.1.3 Open Problems
Several problems remain to be investigated. The first direction is to specify classes of REWB that admit near-linear-time algorithms. We have shown that 1-use REWBs admit a near-linear-time algorithm, whereas 2-use 2-REWBs and ω-use 1-REWBs are unlikely to admit such algorithms. However, the matching complexity of r-use 1-REWB for any constant r ≥ 2 remains open.
The second direction is to improve our algorithm for the ABCBD problem. The most direct question is whether we can eliminate the remaining logarithmic factor and obtain a truly linear-time algorithm: reducing O(|w| log2 |w|) to O(|w|). Moreover, when REWB E is given as input, our algorithm has an exponential dependency on the expression length |E|. Specifically, it is open whether it is possible to reduce the dependence on |E| to polynomial while preserving near-linear dependence on |w|. Note that, if we allow quadratic dependence on |w|, Nogami and Terauchi [88] already achieves O(|E|2|w|2)-time. Furthermore, as we describe in Section 1.3, our algorithm consists of many building blocks and is therefore quite complex. Simplifying it is a meaningful task both for advancing theoretical understanding and for improving practical implementability.
The third direction is to broaden the scope. Real-world regular expression engines support many features beyond backreferences, such as lookaround [48, 55], greedy and lazy Kleene stars [48, 56], and atomic grouping [48, 54]. Therefore, investigating the complexity of matching regular expressions augmented with such features is important in practice. We believe that these problems are also theoretically interesting, in the same way that the REWB matching problem admits deep algorithmic study, as demonstrated in this paper.
1.2 Related Work
1.2.1 ReDoS
Regular Expression Denial of Service (ReDoS) has been recognized as an important instance of algorithmic complexity attacks [31] since at least 2003 [30]. Outages at Stack Overflow (2016) [101] and Cloudflare (2019) [57] are representative examples, and notably, both incidents were triggered by quadratic behavior of regular expression engines, highlighting that even polynomial complexity can result in severe real-world failures. ReDoS is a common type of DoS attack that is officially cataloged as CWE-1333: Inefficient Regular Expression Complexity [75]. Vulnerabilities continue to be discovered and reported in practice; high-risk examples include [79, 80, 81, 82, 83] from 2021 to 2024. In 2025, notable entries in the CVE (Common Vulnerabilities and Exposures, which maintains a public record of disclosed security issues) include [84, 85, 86].
At its core, ReDoS arises from backtracking-based regex engines, which may exhibit catastrophic (possibly exponential) backtracking [53]. This behavior has long been known to automata theorists, and influential books [48] helped disseminate the problem more widely to practitioners. For classical Regex matching, Cox [25, 26] recommended that practitioners prefer Thompson NFA-based implementations over backtracking-based engines, as the former run in O(|E| |w|) time. In contrast, it is unlikely that REWB matching admits such a “silver bullet” solution like the Thompson construction, as this problem is NP-hard in general [3, 12]. This has motivated complexity-theoretic research into the REWB matching problem, including the identification of tractable classes [47, 88, 96].
As an example of ReDoS involving expressions with backreferences, we focus on CVE-2017-16114 [77] and CVE-2019-25103 [78]. Both cases are triggered by an expression that can be abstracted as E := (a∗)x b∗ ((a + b)∗ b) b∗ \x, on which backtracking-based engines take cubic time in the worst case. In CVE-2019-25103, the corresponding patch [19] rewrote E to E1 := (a∗)x ((a + b)∗ b) \x; it modified only the “Regex-part” without touching the “backreference-part”. Consequently, although the ReDoS vulnerability is mitigated, potential vulnerabilities remain, as even the patched version exhibits quadratic time complexity; this issue seems to be an inevitable overhead of backtracking-based engines, as they try all possible prefixes that the variable x captures. In CVE-2017-16114, the corresponding patch [105] rewrote E to E2 := (a∗)x b + (b(a + b)b)∗ \x. Although E2 admits linear-time matching, it alters the accepting language: for example, E and E1 accept a ab a but E2 does not. In contrast, the original expression belongs to our ABCBD problem; thus, it can be evaluated in almost linear time by our algorithm without modifying the semantics.
1.2.2 Hardness of Regular Language Matching Problems
On Regex. While Thompson’s construction [103] solves Regex matching in O( |E||w| ) time, Backurs and Indyk [10, Thm.3] proved that O( (|E||w|)1−ϵ ) time is unachievable under SETH.
Recently, Bringmann et al. introduced the NFA Acceptance Hypothesis [18]: intuitively, for a dense NFA A, the membership problem w ∈ L (A) cannot be solved in O( (|A||w|)1−ϵ ) time for any ϵ > 0. Bille and Gørtz [13] introduced a parameter called density ∆ (the total number of active states during the simulation on the input w) and proved that matching for sparse NFAs (or Regexes) also cannot be solved in O(∆1−ϵ) time under SETH. These results suggest that improving upon the textbook O(|E||w|)-time algorithm for Regex matching is unlikely at present.
On REWB. The REWB matching problem is known to be NP-complete [3, Thm 6.2] when the REWB expression is a part of the input, even over a unary alphabet [12]. Moreover, when parameterized by the number of variables k, the k-REWB matching problem is W[1]-hard [43, Thm. 1]. In fact, W[1]-hardness already holds for a more restricted fragment of REWB called pattern languages [43, Thm. 1][102, Thm. 1]. We briefly recall pattern languages below to relate them to REWB and summarize known algorithmic results.
1.2.3 Algorithms for Regular Expression Matching Problems
On REWB. The current best-known algorithm for the k-REWB matching problem is based on dynamic programming and runs in O(|E| · |w|1+2k) time [35, §IX.C]. Applying this algorithm to the ABCBD problem yields an O(|E| · |w|3)-time algorithm. Nogami and Terauchi gave an O(|E|2|w|2)-time algorithm, and thereby improved the dependence on |w| from cubic to quadratic. As noted earlier, our Theorem 7 further improves the dependence on |w| to near-linear.
Freydenberger and Schmid [47] considered the matching problem for the class of deterministic REWBs, which is a subclass of REWBs that can deterministically match strings when reading from the left. They gave an O(k|w|)-time algorithm for k-REWB. Schmid [96] extended this result to the wider class of memory-deterministic REWBs and gave an O(|E|c|w|)-time algorithm for some constant c. They also refined the time complexity of the REWB matching problem to O(|E| · |w|O(α)) for the cases of small α, where α (≤ k) denotes the active variable degree, which represents the maximum number of variables that are “active” at the same time.
Pattern Language and Word Equation. A pattern language is a class of languages generated by patterns, that is, strings that may also contain variables that can be matched to strings. For example, the pattern P := 01X10X over Σ = {0, 1} with a variable X generates the language { 01w10w : w ∈ Σ∗}. This concept was introduced by Angluin in the late 1970s in the context of learning theory and has since been studied extensively [6, 7, 74, 99].
Pattern languages can be seen as a very restricted subclass of REWB. Specifically, a pattern language can be expressed as a REWB that: (1) uses a capture group (. . .)x for the first occurrence of each variable x, (2) uses a backreference \x for all subsequent occurrences, and (3) only allows concatenation as the outermost operator (no union or Kleene star over captures/backreferences). For example, the above pattern P equals the REWB 01(Σ∗)X10\X.
The matching problem of pattern languages is NP-complete [6, 7, 39, 67] even for the case with alphabet size 2, each variable occurs at most twice, and each variable can be replaced with a string of length in {0, 1} or {1, 2, 3} [42]. Ibarra et al. gave an O (|P|+|w|)|w|k−1 (k−1)! -time algorithm for the membership problem of k-variable pattern languages, where P is the given pattern expression [63]. In particular, it runs in linear time when k = 1. Fernau et al. [40] gave algorithms for several classes of pattern languages with good properties. Particularly, they showed that for the case of non-crossing (i.e., scopes of different variables do not overlap) pattern languages, the matching problem admits an O(m|w| log |w|)-time algorithm, where m is the number of one-variable blocks occurring in a given pattern [40, Thm 8][41, Thm 4.16]. Observe that our XYαZ problem generalizes the case m = 1 by allowing arbitrary Regexes for X, Y, and Z.
Given two pattern languages (possibly sharing variables), the word equation problem asks whether there is a string that matches both of them. The case that one of the languages contains no variables is equal to the pattern language matching problem. In general, the word equation problem is known to be in PSPACE [94]. For the 1-variable case, Dąbrowski and Plandowski [34] gave an O(m + #X log m)-time algorithm where m is the total size of given patterns and #X is the total number of variable occurrences. Later, in the RAM-model setting, Jeż [64] gave an O(m)-time algorithm using the recompression technique introduced by Jeż [65]. Dąbrowski and Plandowski [33] gave an O(m5)-time algorithm for the 2-variable case. In contrast, the problem becomes significantly harder for k ≥ 3 variables; even for the 3-variable case, it is not even known whether the problem is in NP [66]. Schulz [97] considered a variant of the word equation problem that each variable has a Regex constraint. They proved this variant is decidable; it was later proved to be PSPACE-complete by Diekert et al. [36].
On Regex with Lookaround. Lookaround is one of the features that real-world regular expression engines support, which checks whether a specified pattern exists around the current position, without consuming characters. It is folklore that the language class of Regex equipped with lookaround is regular3; thus, it admits O(|w|) time matching by Thompson’s construction when we only consider the dependence on |w|. Therefore, research concerns the dependence on the expression length |E|, and particularly, focuses on O(|E| · |w|) time algorithms.
3We can convert it to a two-way alternating finite automaton (2AFA) [20], whose language class is regular [71].
Mamouras and Chattopadhyay [73] provided an O(|E| · |w|) time membership algorithm. Chattopadhyay et al. [21] mechanized an algorithm of the same complexity based on [73] and verified its correctness using the proof assistant Rocq (formerly known as Coq). Barrière and Pit-Claudel [11] provided a matching algorithm of the same complexity that is faithful to JavaScript Regex matching semantics. Fujinami and Hasuo [49] provided a matching algorithm of the same complexity, which also supports atomic grouping, which is a practical extension that does not enlarge the language expressiveness [48, 54]. Uezato [104] proved that the membership problem of REWB equipped with lookahead (lookaround that only examines after the current position) is PSPACE-complete.
Gapped Patterns. Another well-studied regular-language formalism, motivated by practical pattern matching applications (rather than REWB), is that of gapped patterns. A typical gapped pattern G has the form
G ≡ p0 Σ[α1, β1] p1Σ[α2, β2] · · · Σ[αm, βm] pm,
where each pi ∈ Σ∗ is a fixed string and Σ[α,β] := {w ∈ Σ∗ : α ≤ |w| ≤ β} is the set of substring whose length lies between α and β. Thus every gapped pattern denotes a regular language and can be expressed as a classical Regex. Matching such patterns, including dictionary variants in which a finite set of gapped patterns is matched against a text, has been studied extensively; see, e.g., [87, 46, 14, 59, 62] and the survey [72]. Particularly relevant from a fine-grained perspective is the work of Amir et al. [5] on dictionary matching with one gap. As the uniformly bounded case, a dictionary D = {G1, G2, . . . , Gn} consist of patterns Gi forms pi1 Σ[α, β] pi2 with common bounds α, β. The task is to report their occurrences for a input text w. Under the 3SUM conjecture [51, 90, 68], for suitable dictionaries, they proved a lower bound of Ω(|w|(β − α)1−o(1) + op) where op is the output size [5, Thm. 5 and Table 2]. Complementing this, they also gave an online reporting algorithm whose running time depends on structural parameters of dictionaries, in particular the degeneracy of the associated bipartite graph [5, Thm. 9].
1.3 Technical Overview of Theorem 7
We provide an overview of our algorithm for Theorem 7, which finds a decomposition w = wA wB wC wB wD with wξ ∈ L (ξ) for ξ ∈ {A, B, C, D}. The following figure summarizes the overall structure.
To streamline our algorithm, we first normalize the input w and expressions so that ϵ ∈ L (D) and the alphabet is binary Σ = {0, 1} in Section 4. Then, we can assume wD = ϵ. In Section 5, we reduce the ABCBD problem to two subproblems: the XYYZ problem (Section 6) and the branching ABCBD problem (Sections 7–12). In the former problem, we consider the case wC = ϵ, i.e., w = wA wB wB wD. In the latter problem, we consider the case where two suffixes wC wB wD and wD satisfy a branching condition; that is, their first letters are distinct. To show that this decomposition covers all cases, we rely on the closure properties of Regex and the equivalence with nondeterministic finite automata (NFAs), as detailed in Section 5.2.
The key structure of the former (XYYZ) problem (our X Yα Z problem with α = 2, Section 6) is that, since wC = ϵ, two occurrences of wB appear consecutively in w as w = . . . wB wB . . .. We crucially exploit the periodicity of w induced by this immediate repetition wBwB. We use Crochemore’s maximal local power enumeration [28, Sec. 9.2][27] (Section 6.1), in combination with the periodic properties of Regex (Section 6.3). This part also yields Theorem 9.
To solve the latter (branching ABCBD) problem (Sections 7–12), we work with the suffix tree of w, STw, or simply ST (see Section 2 for the definition). Each leaf ℓ has an index iℓ of w and corresponds to the suffix w[iℓ .. |w|] (w = w[1] w[2] . . . , w[|w|].) Each inner node v represents the substring given by the path-label from the root. For each v, we maintain the set Iv of all indices iℓ of leaves ℓ in the subtree rooted at v. We note that our suffix tree ST is binary because Σ = {0, 1}.
The key property of the problem is the branching condition. It means that the two paths from the root to ℓwBwCwBwD and to ℓwBwD branch at the node v corresponding to wB (as illustrated in the below figure). Using this property, it suffices to consider the following task: (♣): For each node v, find a pair of suffixes branching at v that induces a feasible decomposition.
Let Hv := Iu, where u is a child of v maximizing the size |Iu|, and define Lv := Iv \ Hv. We employ a classical small-to-large (or heavy-light decomposition) strategy: for each i ∈ Lv we determine whether there exists j ∈ Hv such that the pair (i, j) induces a feasible decomposition. Since v:node |Lv| = O(|w| log |w|), the remaining task of (♣) is to find such an index j ∈ Hv in O(log |w|) time for each i ∈ Lv. We then split the task (♣) into the two cases Right-B and Left-B in Section 7.
In Right-B, for each i ∈ Lv, we consider the case i < j: i.e., the shorter suffix wBwD starts at j. Namely, we search for j ∈ Hv such that w[j .. |w|] = wBwD, illustrated as follows:
(♣R) w = w[1 .. i) wA w[i .. i + |wB|) wB w[i + |wB| .. j) wC w[j .. j + |wB|) wB w[j + |wB| .. |w|] wD .
In Left-B, we consider the case j < i where j is the starting position of the longer suffix wB wC wB wD. We search for j ∈ Hv such that w[j .. |w|] = wBwCwBwD, illustrated as follows:
(♣L) w = w[1 .. j) wA w[j .. j + |wB|) wB w[j + |wB| .. i) wC w[i .. i + |wB|) wB w[i + |wB| .. |w|] wD .
To handle both cases, we use the same high-level approach: traverse ST bottom-up and maintain the sets Hv using suitable data structures. Since the concrete algorithms and data structures differ between the two cases, we present them separately.
Right-B Case (Sections 8 and 9). Let v be a node of ST and wB be the string represented by v. Let i ∈ Lv, where w[i .. |w|] corresponds to wBwCwBwD. We assume w[1 .. i) ∈ L (A) and wB ∈ L (B) because otherwise there is no feasible solution. Our task (♣R) is to find an index j ∈ Hv such that w[j .. |w|] corresponds to wBwD. To treat the constraint wC ∈ L (C), we manage Hv using a data structure that answers whether there is an index j ∈ Hv with i < j such that w[i + |wB| .. j) ∈ L (C). We call this structure RightEnumerator (Section 9).
However, this is not yet sufficient, as we must also enforce the constraint wD ∈ L (D). Crucially, whether a fixed index j satisfies this constraint depends on the current node v. This is because the substring corresponding to wD begins at j + |wB|, and this starting position shifts as the length |wB| varies with v. Consequently, we must handle the constraints for both C and D simultaneously. To address this, we partition Hv into subsets such that all indices in the same subset share the same validity regarding D (Section 8). Leveraging the fact that Regex admits a finite transition monoid (see Section 2 for definition), we can ensure that we need to maintain only a constant number of subsets. By maintaining a separate instance of RightEnumerator for each subset and merging them using a disjoint set union data structure, we can resolve the issue and handle this case.
A simple way of constructing RightEnumerator is to use a segment tree, where each node is equipped with the set of elements of transition monoids (Section 9). This yields an O(|w| log3 |w|)-time algorithm. In our algorithm, employing a factorization forest (see Section 2 for definition), we further eliminate one logarithmic factor and achieve O(|w| log2 |w|) time.
Left-B Case (Sections 10–12). Let v be a node of ST and wB be the substring represented by v. Let i ∈ Lv, where w[i .. |w|] corresponds to wBwD. We assume wB ∈ L (B) and wD ∈ L (D) because otherwise there is no feasible solution. Our task (♣L) is to find an index j ∈ Hv with j < i such that w[j .. |w|] corresponds to wBwCwBwD. Moreover, we can handle the constraint for A simply by managing only indices j ∈ Hv with w[1 .. j) ∈ L (A) (recall that, unlike the Right-B case, it is independent of v). The remaining task is to find j satisfying j + |wB| < i and w[j + |wB| .. i) ∈ L (C). We treat it as a data structure problem (Section 10.2). We note that RightEnumerator is insufficient for our purpose, since the constraint j + |wB| < i depends on |wB|, which varies with the current node v.
To address the problem, we consider the following two subcases separately:
near-j: j + |wB| ≤ i < j + 2|wB|, far-j: j + 2|wB| ≤ i.
In the near-j case (Section 12), we derive a periodicity for wB because, for any two indices j, j′ in the near-j case, the substrings w[j .. j + |wB|) and w[j′ .. j′ + |wB|) overlap. With the periodicity inherent to Regex, we can efficiently solve the near-j case in O(log |w|) time. On the other hand, in the far-j case, the index j is “sufficiently far” from i. Technically, the condition j + 2|wB| ≤ i implies that the distance between j + |wB| and i is at least |wB|; we use this margin for the design of our data structure.
To solve the far-j case, we adopt the following strategy. We first build a data structure AuxiliaryEnumerator (Section 11), that maintains intervals [j .. k) as the item [j, k) while ensuring j + |wB| ≤ k. Given i, it answers whether there is an interval [j, k) such that w[j + |wB| .. i) ∈ L (C) and k ≤ i. For the condition j + 2|wB| ≤ i, it suffices to ensure k ≤ j + 2|wB| holds at any moment. The issue is that as we traverse ST, the node v changes (thus, |wB| decreases), so the condition k ≤ j + 2|wB| will be violated. To resolve this issue, when the violation occurs (the margin k − (j + |wB|) becomes at least |wB|), we “re-insert” the new interval [j, k′) to the data structure, where k′ := j + |wB|. The total overhead cost is O(log |w|) time because “re-insertion” happens only after |wB| is halved; this is ensured by the “far-j” condition.
The remaining task is to construct AuxiliaryEnumerator (Section 11). This is similar to RightEnumerator, but requires additional mechanisms to quickly answer queries of w[j + |wB| .. i) ∈ L (C), which depends on the current v (and thus, wB). We adopt a lazy update strategy for this purpose. As in RightEnumerator, using the segment tree leads to the time complexity O(|w| log3 |w|), which can be accelerated to O(|w| log2 |w|) using the factorization forest.
1.4 Organization
The rest of this paper is organized as follows. In Section 2, we introduce the necessary preliminaries and algorithmic tools we use in this paper, while we give some proofs in Appendix A for the sake of self-containment. In Section 3, we establish our hardness results by proving Theorems 3, 4, and 5. As discussed in Section 1.3, Sections 4–12 concentrate on proving Theorem 7. Theorem 9 is proved in Section 6 as a corollary. In Appendix B, we prove Theorem 6. In Appendix C, we analyze the hidden constants of Theorems 7, 8, and 9.
2 Tools and Preliminaries
Integers. We write Z for the set of all integers and write Z≥0 for {i ∈ Z : i ≥ 0}. For an integer n ≥ 1, we write [n] to denote the set {1, 2, . . . , n}.
Strings. Let Σ be a finite alphabet. We write Σ∗ for the set of all finite strings over Σ and ϵ for the empty string. For w ∈ Σ∗, |w| is its length. We use 1-based indexing: for an index i ∈ {1, . . . , |w|}, w[i] is the i-th character of w.
For indices i, j ∈ {1, . . . , |w|} with i ≤ j, w[i .. j] := w[i] w[i + 1] . . . w[j] is the substring from i to j, inclusive. We define w[i .. j] := ϵ if i > j for convenience. For example, if w = abcd, then |w| = 4, w[1] = a, w[4] = d, w[2 .. 2] = b, w[2 .. 4] = bcd, and w[2 .. 1] = ϵ. We also write w[i .. j) for the shorthand for w[i .. j − 1]. It is convenient to extract the ℓ-length substring starting from i. For example, if w = abcd, then w[1 .. 1 + 3) = abc, w[2 .. 2 + 3) = bcd, and w[1 .. 1 + 0) = ϵ. We similarly define w(i .. j] for w[i + 1 .. j].
For a string u and an integer k ∈ Z≥0, we write uk for the string obtained by k-power of u. For example, (abaa)2 = abaa abaa. We naturally extend this notation to ur/|u| with a rational r/|u| ≥ 0. For example, (abaa)34 = aba and (abaa)2+24 = abaa abaa ab.
If w[i] = w[p + i] for all i ∈ {1, 2, . . . , |w| − p}, then we say that w has a period p. Alternatively, if a prefix u of w satisfies w = ur for some r ≥ 1, w also has a period |u|. For example, w = abaa abaa ab has three periods: (i) 4 for w = (abaa)2+24; (ii) 8 for w = (abaaabaa)1+28; (iii) 10 = |w| for w = w1.
The following theorem is well-known and quite useful property on periodic strings. It is sometimes called Fine and Wilf’s theorem [44].
Lemma 10 ([22, Cor. 6.1]). Let w be a non-empty word. If w has two periods p and q and |w| ≥ p + q − gcd(p, q), then w also has a period gcd(p, q).
Regex: Classical Regular Expressions. Let Σ be a fixed finite alphabet.
The calculus of (classical) regular expressions, Regex, is defined by the following grammar:
E ::= ∅ | ϵ | σ | E1 + E2 | E1 · E2 | E∗.
where σ ∈ Σ.
The language of Regex, L (·), is defined as follows:
L (∅) = ∅, L (e) = {e} e ∈ {ϵ, σ}, L (E1 + E2) = L (E1) ∪ L (E2) , L (E1 · E2) = L (E1) · L (E2) , (where X · Y = {xy : x ∈ X, y ∈ Y}) L (E∗) = i≥0(L (E))i
where L0 = {ϵ} and Lk+1 = Lk · L for k ≥ 0; i.e., Lk is the k-th power of L.
We define the size of a regular expression E, denoted |E|, as the total number of occurrences of operators (such as union, concatenation) and operands (alphabet symbols, ϵ, and ∅) that appear in E. The length of the string representation of E is then clearly bounded by O(|E|).
REWB: Regular Expressions with Backreferences. The calculus of extended regular expressions REWB is an extension of Regex with backreferences. Let V be a finite set of variables. Then, the grammar of REWB over V is the following:
E ::= ∅ | ϵ | σ | E1 + E2 | E1 · E2 | E∗ | (E)x | \x
where x ∈ V. We write k-REWB to denote the set of REWBs that have k variables.
We define the semantics of REWB via the semantic function Eλ and then define the language. For a REWB E and a valuation λ from V to Σ∗, Eλ returns a set of pairs ⟨w, λ′⟩ consisting of a matched string and an updated valuation:
ϵλ := { ⟨ϵ, λ⟩ }, σλ := { ⟨σ, λ⟩ }, ∅λ := ∅, E1 · E2λ := {⟨w1w2, ν⟩ : ⟨w1, µ⟩ ∈ E1λ, ⟨w2, ν⟩ ∈ E2µ}, E1 + E2λ := E1λ ∪ E2λ, E∗λ := k≥0Ekλ, where E0 := ϵ, Ek+1 := EkE, (E)x λ := {⟨w, µ[x := w]⟩ : ⟨w, µ⟩ ∈ Eλ}, \xλ := {⟨λ(x), λ⟩}.
This function is well-founded for the height of Kleene stars. This definition follows the formalization in [104].
Let ι be the initialized valuation that maps every variable to the empty string ϵ: i.e., ι(v) = ∅ for all v ∈ V. We simply write E to denote Eι.
We define the language of a REWB E, L (E), as follows:
L (E) := {w : ⟨w, λ⟩ ∈ E}.
If every computation generated by an expression E reads from variables at most R times in total, we say E is R-use.
REWB Example. For example, the following expression E1 is a 1-REWB because there only exists a variable x:
E1 = (Σ∗)x # Σ∗ \x Σ∗.
The language of E1 is L (E1) = {wpat#w1wpatw2 : wpat, w1, w2 ∈ Σ∗}, and it is called a pattern searching language because, if wpat#w is matched with E1, then wpat appears in w. The above E1 is 1-use because every computation read x once by \x.
ϵ-NFA: Nondeterministic finite automata with ϵ-transitions. An ϵ-NFA A is a tuple A = (Q, Σ, ∆, E, q0, F) where Q is a finite set of states, Σ is an input alphabet, ∆ ⊆ Q × Σ × Q is a set of transition rules, E ⊆ Q × Q is a set of ϵ transitions, q0 ∈ Q is the initial state, and F ⊆ Q is a set of final (accepting) states. We write p σ − → q for each transition element (p, σ, q) of ∆ and p ϵ − → q for (p, q) ∈ E. A rule p σ − → q means that we can move to q from p by consuming a letter σ. We write p ϵ = ⇒ q if we can reach q from p only using ϵ-transitions p ϵ − → · · · ϵ − → q. We also write p σ = ⇒ q if we can move to q from p by only consuming a letter σ: i.e., we have a sequence of transitions of the form p ϵ = ⇒ p′ σ − → p′′ ϵ = ⇒ q.
If E = ∅, we call A an ϵ-free NFA. We write ∆(p, σ) to denote the set of states reachable from p by σ: i.e., ∆(p, σ) := {q : p σ − → q}. If E = ∅ and |∆(p, σ)| = 1 for all (p, σ) ∈ Q × Σ, we call A a deterministic automaton (DFA).
The language of A, L (A), is the set of words accepted by A and formally defined as follows:
L (A) := {σ1σ2 . . . σn : q0 σ1 = ⇒ q1 σ2 = ⇒ · · · σn = ⇒ qn, qn ∈ F}.
If q0 ϵ = ⇒ qF, the empty string ϵ belongs to L (A).
By the well-known Thompson’s construction, every regular expression E can be translated in linear time into a sparse ϵ-NFA NE.
Proposition 11 (Thompson’s construction [103][95, Sec. 5]). Let E be a Regex over an alphabet Σ. We can translate E to a corresponding sparse ϵ-NFA NE = (Q, Σ, ∆, E, q0, F) in O(|E|)-time where L (E) = L (NE) and |Q| = |∆| = |E| = O(|E|).
Proposition 12 (Product Construction of ϵ-NFA). Let A = (QA, Σ, ∆A, EA, qA0, FA) and B = (QB, Σ, ∆B, EB, qB0, FB) be ϵ-NFAs, where ∆A, EA, ∆B, EB are represented by adjacency lists. Then, there exists an ϵ-NFA C such that L (C) = L (A) ∩ L (B). In particular, we can construct C in O(|QA| · |QB| + |∆A| · |∆B| + |EA| · |QB| + |QA| · |EB|) time.
Proof. This follows from the classical product construction for DFA and (ϵ-free) NFA (c.f. [95, Sec. 5]). For completeness, we define the construction for our product ϵ-NFA C = (QC, Σ, ∆C, EC, qC0, FC) as follows:
QC := QA × QB, ∆C := {(p, q) σ − → (p′, q′) : p σ − → p′, q σ − → q′}, EC := {(p, q) ϵ − → (p′, q) : p ϵ − → p′} ∪ {(p, q) ϵ − → (p, q′) : q ϵ − → q′}, qC0 := (qA0, qB0), FC := FA × FB.
By the construction, L (C) = L (A) ∩ L (B) trivially holds. Note that adding {(p, q) ϵ − → (p′, q′) : p ϵ − → p′, q ϵ − → q′} to EC does not change L (C), since such a move is simulated by two ϵ-steps.
Regarding the time complexity, we can construct QC in O(|QA| · |QB|) time. Since the transitions are represented by adjacency lists, we can construct ∆C in O(|∆A| · |∆B|) time by iterating over matching transitions. Similarly, we can build EC in O(|EA| · |QB| + |EB| · |QA|) time.
Proposition 13 (Removal of the ϵ word from ϵ-NFA’s language). Let A = (QA, Σ, ∆A, EA, qA0, FA) be an ϵ-NFA. Then, there exists an ϵ-NFA B such that L (B) = L (A) \ { ϵ }. In particular, we can construct B in O(|QA| + |∆A| + |EA|) time.
Proof. We construct an ϵ-NFA B = (QB, Σ, ∆B, EB, qB0, FB) step-by-step. First, we define the set QB as follows:
QB := {(q, 0), (q, 1) : q ∈ QA},
We define ∆B and EB to satisfy the following condition:
• A state (q, 0) represents that the automaton has reached q from the initial state by using only ϵ-transitions.
• A state (q, 1) means that we can reach q from p by using some non-ϵ-transitions.
Therefore,
∆B := {(p, i) σ − → (q, 1) : p σ − → q, i ∈ {0, 1}}, EB := {(p, i) ϵ − → (q, i) : p ϵ − → q, i ∈ {0, 1}}.
We define qB0 := (qA0, 0) and FB := FA × {1}.
If w ∈ L (A) and w = σw′, then we have a decomposition of the following form:
qA0 ϵ = ⇒ q σ − → q′ w′ = ⇒ r ∈ FA.
This computation is simulated in B as follows:
qB0 = (qA0, 0) ϵ = ⇒ (q, 0) σ − → (q′, 1) w′ = ⇒ (r, 1) ∈ FB.
By this observation, L (A) \ {ϵ} ⊆ L (B) clearly holds. Conversely, if B accepts w, then the accepting run must reach some state in FA × {1}, hence it uses at least one labeled transition; projecting the run to the first component yields an accepting run of A on w, so w = ϵ and w ∈ L (A).
Regarding the time complexity, we can construct QB in O(|QA| time. Since the transitions are represented by adjacency lists, we can construct ∆B in O(|∆A|) time and EB in O(|EA|) time.
Remark: The standard ϵ-elimination procedure first computes ϵ-closures (the reflexive transitive closure) of E and then uses them to redirect labeled transitions and accepting states so as to remove ϵ-transitions. When E is given as adjacency lists, computing all ϵ-closures by running a BFS graph search from every state takes O(|Q| (|Q| + |E|)) time in the worst case. Alternatively, representing E as an |Q| × |Q| Boolean adjacency matrix allows one to compute its transitive closure in O(|Q|3) time via the Floyd-Warshall algorithm, or in O(|Q|ω log |Q|) time via fast Boolean matrix multiplication [50, 76, 45]. In contrast, Proposition 13 addresses the weaker task of removing only the empty word ϵ from the language (without eliminating ϵ-transitions), and it runs in linear O(|Q| + |∆| + |E|) time without computing the ϵ-closure.
Ultimately Periodic Set. A set P of non-negative integers is ultimately periodic if there is 4-tuple (µ, M, λ, T) where
• µ is a non-negative integer and M ⊆ {0, 1, . . . , µ − 1}; and
• λ is a positive integer and T ⊆ {0, 1, . . . , λ − 1}
and the following holds:
n ∈ P ⇐⇒ n ∈ M if n < µ, (n mod λ) ∈ T otherwise.
The class of ultimately periodic sets enjoys several closure properties. In this paper, we will use the following ones in [52], for which we give a proof in Appendix A for self-containedness.
Lemma 14. Let P and Q be two ultimately periodic sets. Then, we have the following.
• The union P ∪ Q is ultimately periodic.
• The Minkowski sum P + Q := {p + q : p ∈ P, q ∈ Q} is ultimately periodic.
• For any positive integer e, the set e · P := {ep : p ∈ P} is ultimately periodic.
Monoid. A monoid M is a tuple (M, ⊙, 1M) where M is a base set, ⊙ : M × M → M is an associative binary function — (m1 ⊙ m2) ⊙ m3 = m1 ⊙ (m2 ⊙ m3) for any m1, m2, m3 ∈ M — and 1M is the identity element — m ⊙ 1M = 1M ⊙ m = m for any m ∈ M. An element e ∈ M is idempotent if e ⊙ e = e holds. By definition, the identity element 1M is idempotent, but the opposite direction does not necessarily hold.
The following objects are typical examples of monoids: (1) The set of all strings of Σ∗ forms an infinite monoid (Σ∗, •, ϵ) where_ • _ is concatenation: i.e., w1 • w2 = w1w2. (2) The set of all mappings XX = {f : X → X} on a set X forms a monoid (XX, ◦, idX) where ◦ is the function composition and idX is the identity function. (3) The set of non-negative integers with addition (Z≥0, +, 0) forms an infinite monoid.
Let M = (M, ⊙, 1M) be a monoid, m ∈ M be an element of M, and X, Y ⊆ M be subsets of M. We naturally extend the monoid operator ⊙ to sets as follows:
m ⊙ X := {m ⊙ x : x ∈ X}, X ⊙ m := {x ⊙ m : x ∈ X}, X ⊙ Y := {x ⊙ y : x ∈ X, y ∈ Y}.
Let M1 = (M1, ⊙1, 1M1) and M2 = (M2, ⊙2, 1M2) be monoids. If a function ϕ : M1 → M2 has the following property, it is a monoid homomorphism:
ϕ(a ⊙1 b) = ϕ(a) ⊙2 ϕ(b).
Example. Let M∞ be the monoid formed by the set of all strings Σ∗ with concatenation and M2 be the infinite monoid of the non-negative integers Z≥0 with addition +. Then, the length function ℓ : M1(= Σ∗) → M2(= Z≥0) is a monoid homomorphism, as ℓ(w1w2) = ℓ(w1) + ℓ(w2) for any string w1 and w2.
Transition Monoids. Let M = (M, ⊙, 1M) be a finite monoid, S (⊆ M) be a subset of M, and α : Σ∗ → M be a monoid homomorphism. A language L ⊆ Σ∗ is recognized by the triple (M, S, α) if L = α−1(S) = {w : α(w) ∈ S}. In this case, we refer to M as a transition monoid of L. 4 The following classical result connecting regular languages and recognizability by finite monoids is fundamental in automata theory.
4Traditionally, a transition monoid is a transformation monoid T ⊆ XX (under function composition) on some set X. T is typically generated by the transition maps of an automaton (particularly, of a DFA). Given a recognizing triple (M, S, α), we obtain a transformation monoid on X = M via the right action ρw(m) := m ⊙ α(w). Indeed, w ∈ L ⇐⇒ α(w) ∈ S ⇐⇒ ρw(1M) ∈ S. Thus, we use “transition monoid” for M as a mild abuse of terminology.
Proposition 15 ([93, 92][95, Chap. II]). Let L ⊆ Σ∗ be a language. The following conditions are equivalent:
1. L is regular: i.e., there exists a Regex A or an ϵ-NFA A such that L = L (A).
2. L is recognized by some triple (M, S, α).
For a Regex E, the standard construction—translating E to an NFA, determinizing it to a DFA, and then taking the transition monoid—yields a transition monoid of size at most NN with N = 2O(|E|), and hence at most 22O(|E|).
The following explicit construction yields a smaller transition monoid of size 2O( |E|2 ).
Lemma 16 ([17, 61]). Let E be a Regex over an alphabet Σ. There exists a triple (M, S, α) that recognizes L (E). In particular, the size of M is 2O(|E|2) and we can construct it in 2O(|E|2) time.
Proof. By Proposition 11, we can construct an ϵ-NFA A for E with O(|E|) states and transitions in time O(|E|). Moreover, by computing the ϵ-closure of A, we can construct an ϵ-free NFA B such that L (E) = L (B) in time polynomial in the size of A. In particular, A and B have the same set of states.
From the ϵ-free NFA B, we construct our Boolean matrix monoid M as follows. We write B = (Q, Σ, ∆, E = ∅, q0, F). For each σ ∈ Σ, let Mσ be the |Q| × |Q| Boolean matrix defined by Mσp,q = 1 iff (p, σ, q) ∈ ∆. Let M be the submonoid of {0, 1}Q×Q generated by {Mσ : σ ∈ Σ} under Boolean matrix multiplication — using the Boolean OR ∨ as addition and the Boolean AND ∧ as multiplication — with the identity element given by the identity matrix I.
Now we define our monoid homomorphism α : Σ∗ → M as follows:
α(σ) := Mσ.
Observe that w ∈ L (B) iff there exists qf ∈ F with (α(w))q0,qf = 1. Therefore, letting
S = {X ∈ M : ∃q ∈ F. Xq0,q = 1},
the triple (M, S, α) recognizes L (B) and thus L (E).
Finally, since M ⊆ {0, 1}Q×Q, we have |M| ≤ 2|Q|2. Since |Q| = O(|E|), this yields |M| = 2O(|E|2), and M can be constructed by closing {I} ∪ {Mσ : σ ∈ Σ} under multiplication, in time polynomial in |M| and |Q|.
Relational Transition Monoid TE and Associated Homomorphism ∆E of Regex E.
Let E be a Regex, and let (M, S, α) be the recognizing triple constructed in Lemma 16 for E.
Hereafter, we refer to the Boolean matrix monoid M as the (relational) transition monoid of E and write TE to denote M. Moreover, we write ∆E to denote the homomorphism α and set SE := S. With this notation, we have the following:
w ∈ L(E) ⇐⇒ ∆E(w) ∈ SE.
Factorization Forest. Let E be a Regex. Consider the following range evaluation problem over a fixed domain.
1. We receive a domain (string) w and perform some pre-processing for w.
2. For each query (i, j) with 1 ≤ i < j ≤ |w|, we decide if w[i .. j] ∈? L (E) in O(1) time for fixed E.
To answer every query in O(1) time for fixed E, we employ factorization forests [16, 23, 100].
Let Σ be a finite alphabet, M be a finite monoid, and ϕ : Σ∗ → M be a homomorphism from the set of strings Σ∗. Let w = σ1σ2 . . . σN ∈ Σ+ be a non-empty string. A ϕ-factorization forest of w (Ramseyan factorization tree), denoted by FFϕ(w), is an ordered rooted tree in which a letter is assigned to each leaf, and reading those letters on leaves from left to right yields w. Each node v is annotated by a value ν(v) ∈ M and corresponds to a contiguous factor of w. The annotation ν(·) satisfies the following condition:
Leaf If v is a leaf with letter σi, then ν(v) = ϕ(σi).
Binary If v has two children c1 and c2, then ν(v) = c1 ⊙ c2.
Idempotent If v has at least three children c1, c2, . . . , cm, then ν(c1) = ν(c2) = · · · = ν(cm) = e is an idempotent element. It also holds that ν(v) = e due to the idempotency of e.
For each node v of the factorization forest, we write [ℓv, rv) to denote the interval exactly covered by v, {ℓv, ℓv + 1, . . . , rv − 1}, where ℓv refers to the leftmost index managed by the node v and rv refers to the index immediately to the right of the rightmost index managed by the node v.
Example of Factorization Forest. Consider the following NFA N over Σ = {a, b}.
This automaton is actually a DFA and has four states q0, q1, q2, and ⊥. This DFA recognizes the language b∗ab∗ab∗: i.e., the set of words that contain exactly two occurrences of a.
There are two base monoid elements (matrices) δa and δb of the relational transition monoid of N, which correspond to the sets of transitions by the letters a and b:
δa = , δb = .
By composing these two matrices by using the Boolean matrix multiplication (⊙), we obtain the following two elements:
δ2 = , δ3 = .
For example, δ2 = δa ⊙ δb and δ3 = δ2 ⊙ δa. There are no other matrices in the transition monoid; therefore, TN = ({δa, δb = 1, δ2, δ3}, ⊙, 1) where 1 is the identity matrix.
Let us consider the following factorization forest over a string aaababaabaaabbbbb:
For simplicity, we do not display the values for the leaf nodes. Assume every leaf (i.e., letter σ) has ν(σ) = δσ.
Then, we can easily check (1) that every binary node n has the correct value ν(c1) ⊙ ν(c2) using its child c1 and c2; and also (2) for the two idempotent nodes, δ3 = δ3 ⊙ δ3 ⊙ δ3 holds and also δb = δb ⊙ δb ⊙ δb ⊙ δb holds.
The (red) idempotent node v labeled with δ3 covers the interval [1, 2, . . . , 12]. Thus, we write [ℓv, rv) = [1, 13). Similarly, the idempotent node v′ labeled with δb covers the interval [14, 15, 16, 17]; thus, [ℓv′, rv′) = [14, 18). Every leaf node ℓi of the index i exactly covers [i]; thus, [ℓi, ri) = [i, i + 1).
There are multiple factorization forests for a single string. For every monoid homomorphism ϕ : Σ∗ → M from Σ∗ to a finite monoid M, the following result ensures that we can effectively compute a factorization forest FFϕ(w) for a given string w in linear time O(|w|). Moreover, the height of the factorization forest does not depend on w; indeed, it just depends on M.
Lemma 17 (Factorization Forest[15, 23, 69, 70, 100]). Let M = (M, ⊙, 1M) be a finite monoid and λ be the computational cost of performing ⊙ once. For every word w ∈ Σ∗, there is a FFϕ(w) of height ≤ 3|M|, which depends only on M, but not on w or ϕ. Moreover, we can compute FFϕ(w) in O(|M|3 · λ + |M||w|) time5.
5Although Kufleitner does not mention the detailed time complexity in [69, 70], we can obtain the time complexity O(|M|3 · λ + |M| · |w|) as follows. We first compute the data structure for J-class (Green’s relation), which is a basic tool to build factorization forests, in O(|M|3 · λ). Then we can build FFϕ(w) in O(|M| · |w|) time using the recursive procedure in [69].
We also refer to the following application of factorization forests.
Lemma 18 (Range Evaluation[15, 23]). Let w ∈ Σ∗ be a string, ϕ : Σ∗ → M be a monoid homomorphism, and FFϕ(w) be a factorization forest of w and ϕ. Then, we can compute ϕ(w[i .. j]) in O(h · λ)-time, where h is the height of FFϕ(w) and λ is the computational complexity of the monoid operation cost of M.
(Proof Sketch). We search nodes in FFϕ(w) top-down to exactly cover w[i .. j]. Efficiently using idempotent nodes, we can achieve O(|M|) monoid operations; therefore, we totally need O(|M| · λ)-time. For more detailed construction, refer to [15, Section 4] and [23].
Suffix Tree. The suffix tree [28, 29, 58] STw of a string w is an edge-labeled rooted tree such that
• each edge is equipped with a substring of w, and
• for each index i ∈ [|w|], there is a node v such that the string obtained by concatenating the strings on the edges on the root-v path (in this order) coincides with the suffix w[i .. |w|].
For a given string w, STw can be computed in linear time O(|w|), where labels on edges are represented by intervals.
We use the following notation:
• Γ(v): The path label of v: i.e., the string obtained by concatenating the edge labels on the path from the root to v.
• isSuffix(v): A binary flag indicating whether Γ(v) is a suffix of w. Specifically, isSuffix(v) = 1 if and only if Γ(v) is a suffix of w.
For a suffix node v (i.e., isSuffix(v) = 1), we define Occ(v) as the starting position of the suffix Γ(v) in w: Occ(v) := |w| − |Γ(v)| + 1. For a node v, we write STw[v] for the subtree of STw rooted at v.
Remark. Throughout this paper, we consider suffix trees without appending the special end-marker symbol $. In particular, some suffixes may end at internal nodes; we mark such nodes with a Boolean flag isSuffix(v), which is 1 iff the path label Γ(v) is a suffix of w.
Example of Suffix Tree. Let us consider the suffix tree for the following string of length 10:
w = index 1 2 3 4 5 6 7 8 9 0 letter a a b a a b a b b a
This figure puts an integer i to a suffix node v (i.e., isSuffix(v) = 1) where i = Occ(v). As the figure shows, every leaf node is labeled with an integer i where 1 ≤ i ≤ |w|. A leaf labeled with i corresponds to the suffix of w starting at position i. For example, the leaf ℓ5 labeled 5 represents the suffix starting from 5, i.e., w[5 .. |w|] = ababba, and its path-label is Γ(ℓ5) = a b a bba.
In addition to leaves, some inner nodes are also labeled with integers. For example, the nodes labeled 9 and 10 in the figure correspond to suffixes of w. Let n9 and n10 denote these nodes. Then Γ(n9) = ba and Γ(n10) = a, both of which are suffixes of w. It follows that Occ(n9) = 9 and Occ(n10) = 10.
The subtree STw[n10] contains all suffixes of w that start with the letter a = Γ(n10). Similarly, the subtree STw[n9] contains all suffixes of w that start with the string ba = Γ(n9)
Remark: Unlike the above illustration, every actual edge from a node v to its child u, denoted v (l,r) − → u, is labeled a pair of integers 1 ≤ l ≤ r ≤ |w|. The pair (l, r) represents the substring w[l .. r]. This path compression is crucial to build the suffix tree in linear time. It is noteworthy that on the paths from a node v to two of its children, u1 and u2, where v (l1,r1) − → u1 and v (l2,r2) − → uw, the first characters of the edge labels must be different, i.e., w[l1] = w[l2] holds.
Heavy-Light Decomposition (of Suffix Tree). Let ST be the suffix tree of a string w. We classify every edge as either heavy or light as follows. For each non-leaf node u ∈ ST with a left child ℓ and a right child r:
• If | ST[ℓ] | ≥ | ST[r] | (i.e., the number of nodes in the left subtree ≥ the number of nodes in the right subtree), then the edge u → ℓ is heavy and the edge u → r is light. In case of equality, the left edge is chosen as heavy by convention.
• Otherwise, the edge u → ℓ is light and the edge u → r is heavy.
For each non-leaf node u ∈ ST with a single child v, the edge u → v is a heavy edge. A heavy path π is a maximal path such that every edge is heavy. The collection of all heavy paths forms a partition of the nodes of ST. We refer to this partition as the heavy-light decomposition of ST.
Example of Heavy Light Decomposition. The left-hand and right-hand sides of the following figure illustrate the heavy-light decomposition of the suffix trees for aabaababba and babbabbba, respectively.
As the figures illustrate, a leaf node may form a heavy path consisting of a single node. All leaf nodes are the bottommost node of some heavy-path and vice versa. Furthermore, if an inner node has only one child, the edge to that child is heavy by definition.
The heavy-light decomposition guarantees the following basic and well-known property.
Proposition 19. Let STw be a suffix tree of a string w, and consider its heavy-light path decomposition. For any node v ∈ ST, the path from the root to v contains O(log |w|) light edges.
From this property, the following useful fact can be derived. Suppose that, for every inner node v ∈ STw, we collect all vertices in the subtree STw[u] rooted at the light child u of v where v → u is a light edge. Then the total cost of this collecting operation, summed over all nodes v, is O(|w| log |w|).
3 Hardness
We show our three hardness results in this section:
1. The REWB matching problem is W[2]-hard (Theorem 3) in Section 3.1.
2. Under a hypothesis for the triangle detection problem, 2-use 2-REWB matching problem cannot be solved in almost linear time (Theorem 4) in Section 3.2.
3. Under SETH (more technically, k-OV Hypothesis), k-REWB matching problem cannot be solved in O(n2k−ϵ) time (Theorem 5) in Section 3.3.
In Section 3.1 and 3.2, we use the following notation. Let G = (V, E) be an undirected graph without self-loops where V is a set of vertices and E is a set of edges. For our constructions, we assume that each vertex v is uniquely encoded as a binary string of length O(log n); that is, v ∈ (0 + 1)+, where E+ := E E∗ denotes one or more repetitions of a REWB E.
For readability, in this Section 3, we sometimes write [E]x instead of (E)x.
3.1 W[2]-hardness for REWB: Reduction from k-Dominating Set Problem
We prove Theorem 3 by reduction from the following k-dominating set problem (k-DSP).
k-DSP: k-Dominating Set Problem Input: An undirected graph G = (V, E) and an integer k. Task: Deciding if there is a k-dominating set: i.e., an (exactly) k-vertex subset of D that satisfies the following condition: ∀v ∈ V. ((v ∈ D) ∨ (∃u ∈ D.(u, v) ∈ E)). We note that, since G is undirected, (u, v) ∈ E ⇐⇒ (v, u) ∈ E. It is known that this problem is W[2]-complete [37] when parameterized by k. Furthermore, the following is known.
Lemma 20 ([91][32, Thm 14.42]). Assuming SETH, there is no algorithm running in O(nk−ϵ) time solving k-DSP for any ϵ > 0.
Our main task is to provide the following reduction from k-DSP to k-REWB matching problem.
Lemma 21 (Reduction from k-DSP to k-REWB Matching Problem). Let k ≥ 1 be an integer. In time O(k), we can construct a k-REWB Ψk of length O(k) satisfying the following.
Let G = (V, E) be an undirected graph. There exists a string G such that the following holds:
G ∈ L (Ψk) ⇐⇒ there is a k-Dominating Set D of G.
In particular, we can construct the string G in O((n + m) log n) time with |G| = O((n + m) log n) where n := |V| is the number of vertices and m := |E| is the number of edges.
From this lemma, we obtain the following W[2]-hardness result.
Theorem 3. When the expression E is part of the input, the REWB matching problem is W[2]-hard parameterized by the expression size |E|.
Proof. We give an FPT-reduction from k-DSP.
Given an instance (G, k), we output the matching instance (Ψk, G), where Ψk is constructed in O(k) time and G is constructed in O((n + m) log n) time as in Lemma 21, such that G ∈ L (Ψk) iff G has a k-dominating set of size exactly k.
Moreover, the parameter of the output instance satisfies |Ψk| = O(k). Hence, this is an FPT-reduction, and the claim follows since k-DSP is W[2]-hard.
We note that this result is stronger than W[2]-hardness parameterized by the number of variables k, since the number of variables k is at most the expression length |Ψk|.
3.1.1 Proof of Lemma 21
To reduce the k-DSP to k-REWB matching problem, we first encode the given graph G = (V, E) into a string. For V = {v1, . . . , vn}, we assume that each vertex vi ∈ {0, 1}+ is a distinct ⌈ log n⌉-bit encoding.
For a vertex v with its adjacency list Adj(v) = {u ∈ V : (v, u) ∈ E} = {u1, . . . , ut}, we define
α(v) := ⟨v⟩ u1 # u2 # · · · # ut # ⟨/v⟩.
For example, if Adj(10) = {1111, 00, 01, 100}, α(10) = ⟨10⟩ 1111 # 00 # 01 # 100# ⟨/10⟩. It is clear that, for each vertex v, |α(v)| = O(ev log n) where ev := |Adj(v)| is the number of edges connected to v.
Then, we define G as a string over an alphabet Σ = {0, 1, #, ♮, @, ⟨, ⟩, /} as follows:
wV := v1 # v2 # · · · # vn #, wE := α(v1) ♮ α(v2) ♮ · · · ♮ α(vn) ♮, G := wV @ wE,
where V = {v1, v2, . . . , vn} with vi ∈ (0 + 1)+. It is clear that |G| = O(n log n) + v∈V |α(v)| = O(n log n + m log n), where n is the number of vertices and m is the number of edges.
Hereafter, we translate the dominating set constraint into a REWB expression. To this end, we introduce our building blocks (expressions) ψpick, ψitself, ψneigh.
We first define ψpick as follows:
ψpick := ψskip (ψV)x1 # ψskip (ψV)x2 # · · · #ψskip (ψV)xk # ψskip
where ψV := (0 + 1)+ and ψskip := (ψV #)∗. Each vertex code is delimited by #, hence ψskip can skip any number of vertices before binding the next one.
The expression ψpick is applied to wV to nondeterministically select k vertices. For example, we consider the following wV:
wV = 0#1#01#10#11#100#
When k = 2, applying ψpick generates the following computation, for example:
ψskip (ψV)x1 0 # # ψskip 1# 01# 10# (ψV)x2 11 # # ψskip 100# .
In particular, after this computation, x1 is bound to 0 and x2 to 11.
From the construction and this explanation, it is clear that, by applying ψpick to wV, we can nondeterministically select all k-vertex combinations and store each combination into k variables x1, x2, . . . , xk. This property of ψpick is formalized as follows.
Proposition 22. For each k-subset U = {u1, . . . , uk} ⊆ V, there exists a match of wV with ψpick such that the variables x1, . . . , xk are bound to the elements of U in the order they appear in wV.
Conversely, in any match of wV with ψpick, the variables x1, . . . , xk are bound to k distinct vertices, hence represent a k-subset of V.
In particular, in any match of wV with ψpick, the string stored in each variable xi is a vertex in V. Hereafter, we write vxi to denote the vertex captured by xi.
We next define the following two expressions for each i ∈ {1, . . . , k}:
ψitself,i := ⟨\xi⟩ ψskip ⟨/\xi⟩, ψneigh,i := ⟨ψV⟩ ψskip \xi # ψskip ⟨/ψV⟩.
To explain these two expressions, suppose that the input head is positioned at the first symbol of α(vi) for some vertex vi within wE = · · · ♮ α(vi) ♮ · · · . Applying ψitself,j in this situation succeeds iff vi = vxj; otherwise the match fails. Similarly, applying ψneigh,j succeeds iff vxj is adjacent to vi.
We formalize the above argument for ψitself and ψneigh as the following proposition.
Proposition 23. Let i ∈ {1, . . . , k} and v ∈ V. Let ui be the vertex stored in the variable xi. Then,
• α(v) matches ψitself,i if and only if ui = v, and
• α(v) matches ψneigh,i if and only if (ui, v) ∈ E.
Using ψitself and ψneigh, we define the following expression ψdominated, which checks whether the selected vertices {vx1, vx2, . . . , vxk} form a dominating set, when applied to wE:
ψdominated := (ψitself,1 + · · · + ψitself,k + ψneigh,1 + · · · + ψneigh,k) ♮∗ .
We show the following property of ψdominated.
Proposition 24. wE matches ψdominated if and only if {vx1, . . . , vxk} is a k-dominating set of G.
Proof. (⇒) Assume that {vx1, . . . , vxk} is a k-dominating set of G. Then, for all v ∈ V, either v = vxi for some i or (v, vxi) ∈ E for some i. Therefore, from Proposition 23, for each v ∈ V, α(v) matches ψitself,1 + · · · + ψitself,k + ψneigh,1 + · · · + ψneigh,k, which is a subexpression of ψdominated. Combining such matching for all v ∈ V yields a matching of wE to ψdominated.
(⇐) Conversely, assume wE matches ψdominated. The assumption means that, for each v ∈ V, the string α(v) in wE is consumed by ψitself,i or ψneigh,i for some i. From Proposition 23, v = vxi holds if α(v) matches ψitself,i and (v, vxi) ∈ E holds if α(v) matches ψneigh,i. Since it holds for all v ∈ V, {vx1, . . . , vxk} is a k-dominating set of G.
Finally, we combine ψpick and ψdominated and obtain our main expression Ψ as follows:
Ψk := ψpick @ ψdominated.
Note that Ψk is a fixed REWB expression depending only on k. The following property of Ψ clearly holds.
Proposition 25. In any match of G against Ψk, the prefix wV is matched by ψpick and the suffix wE is matched by ψdominated.
Proof. The string G = wV @ wE contains exactly one occurrence of @. Hence, in any match with Ψk, this symbol must be consumed by the @ in Ψk, which separates the part matched by ψpick from the part matched by ψdominated.
Combining Propositions 22, 24, and 25 directly yields the following property, which concludes Lemma 21:
G has a k-dominating set iff G matches the k-REWB Ψk (equivalently, G ∈ L (Ψk)).
3.2 Hardness for 2-use 2-REWB: Reduction from Triangle Detection Problem
We prove Theorem 4 by reduction from the following triangle detection problem.
Triangle Detection Problem Input: An undirected graph G = (V, E) with n := |V| vertices and m := |E| edges. Task: Deciding whether G contains a triangle, that is, whether there is a set of three distinct vertices {a, b, c} with (a, b), (b, c), (c, a) ∈ E. The following is conjectured about the triangle detection problem.
Hypothesis (No-Almost-Linear-Time Hypothesis [2, 1]). There is a constant δ > 0, such that in the Word RAM model with words of O(log n) bits, any algorithm requires m1+δ−o(1) time in expectation to detect whether a graph with m edges graph contains a triangle.
In this section, our main task is giving the following reduction from the triangle detection problem to the 2-use 2-REWB matching problem.
Lemma 26 (Reduction from Triangle Detection Problem to 2-use 2-REWB Matching Problem).
There exists a fixed 2-use 2-REWB expression Ψ that solves the triangle detection problem in the following sense:
Let G = (V, E) be an undirected graph with n vertices and m edges. There exists a string G such that the following holds:
G ∈ L (Ψ) ⇐⇒ there is a triangle in G.
In particular, we can construct the string G in O(m log n) time, and the size of G is |G| = O(m log n).
We first show our hardness result from Lemma 26. While the proof follows a standard reduction argument, we provide the details below for completeness.
Theorem 4. Assuming the no-almost-linear-time hypothesis for Triangle Detection, there exists a fixed 2-use 2-REWB expression Ψ such that the matching problem for Ψ cannot be solved in |w|1+δ−o(1) time for some constant δ > 0.
Proof. Assume the No-Almost-Linear-Time Hypothesis holds. Let δ∆ > 0 be the constant specified in the hypothesis; that is, any algorithm requires time m1+δ∆−o(1).
Let Ψ be the fixed 2-use 2-REWB expression from Lemma 21. For every graph G with n vertices and m edges, we can construct G such that G ∈ L(Ψ) ⇐⇒ G has a triangle. We construct a triangle detection algorithm T as follows: Given G, remove isolated vertices so that n ≤ 2m, construct G, and run the matching algorithm A on G.
Suppose for contradiction that there is an algorithm A for Ψ running in time |w|1+δ−o(1) for every δ > 0. Specifically, fix γ := δ∆/2 and assume A runs in time O(|w|1+γ).
The construction of G takes O(m log n) time and yields |G| = O(m log n). Since n ≤ 2m, we have |G| = O(m log m). Running A on G takes the following time TA(G):
TA(G) ≤ O (m log m)1+γ = O m1+γ(log m)1+γ .
Since (log m)1+γ = mo(1), the total running time of T is:
TT(G) = O(m log m) + m1+γ+o(1) = m1+γ+o(1).
Substituting γ = δ∆/2, we get:
TT(G) = m1+δ∆ 2 +o(1).
For sufficiently large m, 1 + δ∆ 2 + o(1) < 1 + δ∆ − o(1). Thus, T solves the triangle detection problem strictly faster than the hypothesized lower bound m1+δ∆−o(1), which is a contradiction.
3.2.1 Proof of Lemma 26
We here encode the given graph G into the following string G over an alphabet Σ = {0, 1, #, ♮, @, ⟨, ⟩, /}:
G := wE @ wE ,
where the string representation of the adjacency lists of G, wE, is defined in the previous section. Therefore, it is clear that the size of |G| satisfies |G| = O(m log n) where n and m are the number of vertices and edges of G, respectively. Moreover, we can construct G in O(m log n) time.
If G has a triangle {a, b, c}, then the following pattern must appear in G:
· · · ⟨a⟩ · · · #b# · · · #c# · · · ⟨/a⟩ · · · @ · · · ⟨b⟩ · · · #c# · · · ⟨/b⟩ · · · .
Conversely, if this pattern appears in G, then G has a triangle {a, b, c}.
We now prepare two expressions ϕpick and ϕcheck where
• ϕpick nondeterministically chooses one vertex v and selects two neighbors and save them to the variables x and y.
• ϕfind searches the adjacency list of the vertex stored in the variable x and then searches the vertex stored in the variable y.
We first define ϕpick as follows:
ϕpick := Υ∗ ⟨ψV⟩ ψskip (ψV)x # ψskip (ψV)y # ψskip ⟨/ψV⟩ Υ∗ @
where ψV := (0 + 1)+, ψskip := (ψV #)∗ (as with Section 3.1), and Υ := Σ \ {@}.
We explain how this expression ϕpick nondeterministically selects and saves two vertices in an adjacency list step-by-step. The part Υ∗ ⟨ψV⟩ nondeterministically consumes a prefix and proceeds to the following part
Υ∗ · · · ⟨ψV⟩ ⟨a⟩ · · · #b# · · · #c# · · · ⟨/a⟩ · · · @ · · · ⟨b⟩ · · · #c# · · · ⟨/b⟩ · · · .
Then the following subexpression ψskip can consume the substring before b as follows:
Υ∗ · · · ⟨ψV⟩ ⟨a⟩ ψskip · · · # b# · · · #c# · · · ⟨/a⟩ · · · @ · · · ⟨b⟩ · · · #c# · · · ⟨/b⟩ · · · .
Now the subexpression (ψV)x# captures b to x successfully:
Υ∗ · · · ⟨ψV⟩ ⟨a⟩ ψskip · · · # (ψV)x b # # · · · #c# · · · ⟨/a⟩ · · · @ · · · ⟨b⟩ · · · #c# · · · ⟨/b⟩ · · · .
Similarly, the subexpression ψskip (ψV)y #ψskip ⟨/ψV⟩ can capture the vertex c to y and successfully reach to the end of the adjacency list ⟨/a⟩ as follows:
Υ∗ · · · ⟨ψV⟩ ⟨a⟩ ψskip · · · # (ψV)x b # # ψskip · · · # (ψV)y c # # ψskip · · · ⟨/ψV⟩ ⟨/a⟩ · · · @ · · · ⟨b⟩ · · · #c# · · · ⟨/b⟩ · · · .
Finally, the part Υ∗@ successfully consumes the first wE as follows:
Υ∗ · · · ⟨ψV⟩ ⟨a⟩ ψskip · · · # (ψV)x b # # ψskip · · · # (ψV)y c # # ψskip · · · ⟨/ψV⟩ ⟨/a⟩ Υ∗ · · · @ @ · · · ⟨b⟩ · · · #c# · · · ⟨/b⟩ · · · .
Υ∗ also never goes beyond @ because @ / ∈ Υ.
This argument immediately leads to the following proposition about ϕpick.
Proposition 27. Applying ϕpick to G = wE @ wE, it consumes the prefix including @ (i.e., wE@) and save two vertices b and c to x and y, respectively, where they are neighbors of some vertex a: that is, a−b and a−c. Moreover, ϕpick can select all such triples (a, b, c).
Our remaining task is designing a subexpression that can find the following pattern when b and c are stored in the variables:
· · · ⟨b⟩ · · · #c# · · · ⟨/b⟩ · · · .
To this end, we define the following expression ϕfind:
ϕfind := Υ∗ ⟨\x⟩ ψskip \y # Σ∗ .
We apply this expression to the rest of the input consumed by ϕpick. The first part Υ∗⟨\x⟩ successfully finds the adjacency list of the vertex stored in the variable x as follows:
Υ∗ · · · ⟨ψV⟩ ⟨a⟩ ψskip · · · # (ψV)x b # # ψskip · · · # (ψV)y c # # ψskip · · · ⟨/ψV⟩ ⟨/a⟩ Υ∗ · · · @ @ · · · Υ∗ ⟨b⟩ ⟨\x⟩ · · · #c# · · · ⟨/b⟩ · · ·
where the variable x now has the vertex b. After entering the adjacency list of b, the part ψskip \y # successfully finds the neighbor stored in the variable y as follows:
Υ∗ · · · ⟨ψV⟩ ⟨a⟩ ψskip · · · # (ψV)x b # # ψskip · · · # (ψV)y c # # ψskip · · · ⟨/ψV⟩ ⟨/a⟩ Υ∗ · · · @ @ · · · Υ∗ ⟨b⟩ ⟨\x⟩ · · · # ψskip c \y # # · · · ⟨/b⟩ · · ·
The success of applying the last part means that we find the triangle {a, b, c}; thus, we finally consume the rest of the input by Σ∗ as follows:
Υ∗ · · · ⟨ψV⟩ ⟨a⟩ ψskip · · · # (ψV)x b # # ψskip · · · # (ψV)y c # # ψskip · · · ⟨/ψV⟩ ⟨/a⟩ Υ∗ · · · @ @ · · · Υ∗ ⟨b⟩ ⟨\x⟩ · · · # ψskip c \y # # · · · ⟨/b⟩ · · · Σ∗ .
This argument immediately leads to the following proposition about ϕfind.
Proposition 28. Assume that the variable x and y stores a vertex b and c, respectively. On the application of ϕfind to wE, the following conditions are equivalent:
• the application results in success with consuming all the input
• the vertices b and c are neighbors
Combining ϕpick and ϕfind, we define our expression Ψ as follows:
Ψ := ϕpick ϕfind.
Propositions 27 and 28 lead to our main property, which concludes Lemma 26:
wE @ wE ∈ L (Ψ) ⇐⇒ there is a triangle in G.
3.3 Hardness from k-Orthogonal Vectors Problem Hypothesis
We here show our O(n2q−ϵ)-time hardness for the q-REWB matching problem where n is the length of input strings under SETH, or more technically, under the k-orthogonal vectors (k-OV) Hypothesis [38, 107], which is weaker than SETH and indeed is implied by SETH. To use k for the k-OV and its hypothesis, we use “q” to denote the number of variables of REWB in this section.
Let v1, v2, . . . , vk ∈ {0, 1}d be d-dimensional 0-1 vectors over the ring Z. The k inner-product is defined as follows:
IPk(v1, v2, . . . , vk) := d i=1 k j=1 vj[i] .
These vectors are k-orthogonal if IPk(v1, v2, . . . , vk) = 0. In our construction, we use the following equivalent condition: d i=1 k j=1(vj[i] = 0).
We now consider the k-OV and the k-OV Hypothesis.
k-OVN,d Problem Input: k sets A1, . . . , Ak ⊆ {0, 1}d where each set Ai has size |Ai| = N. Task: Deciding if the following holds: ∃v1 ∈ A1. ∃ v2 ∈ A2. . . . ∃vk ∈ Ak. IPk(v1, v2, . . . , vk) = 0.
Hypothesis (k-OV Hypothesis [38, Hypothesis 2],[107, Hypothesis 4]). Let k ≥ 2 be an integer. For any ϵ > 0 and every dimension function d(N) = ω(log N) (e.g., d(N) = ⌈log2 N⌉), k-OVN, d(N) cannot be solved in O(Nk−ϵ) time.
Remark: It is known that k-OV Hypothesis is weaker than SETH. Actually, SETH implies k-OV Hypothesis [107, Theorem 3.1] [38, 106]
We provide an efficient reduction from 2k-OV problem to k-REWB matching problem.
Lemma 29. Let k ≥ 1 be an integer. There exists a (fixed) k-REWB Ψk that solves 2k-OV in the following sense: Let N ≥ 1 be an integer and A1, . . . , A2k ⊆ {0, 1}d be an instance of 2k-OV with |A1| = · · · = |A2k| = N. There is a string S(A1, . . . , A2k) such that
S(A1, . . . , A2k) ∈ L (Ψk) ⇐⇒ ∃v1 ∈ A1.∃v2 ∈ A2. · · · .∃v2k ∈ A2k. IP2k(v1, v2, . . . , v2k) = 0.
In particular, we can construct S(A1, . . . , A2k) in O(k · N · d2) time.
Before providing the proof of this lemma (shown in Section 3.3.1), we here prove Theorem 5 using this lemma. While the proof follows a standard reduction argument, we provide the details below for completeness.
Theorem (Reformulation of Theorem 5). The q-REWB matching problem cannot be solved in O(|w|2q−ϵ) time for any ϵ > 0 under k-OV Hypothesis.
Proof. We proceed by contradiction. Suppose there exists an algorithm A solving the problem in time O(|w|2q−ϵ) for some constant ϵ > 0. We construct an efficient algorithm to solve 2q-OVN, d as follows:
1. Given an instance of 2q-OVN, d consisting of 2q sets {A1, A2, . . . , A2q} of N vectors in {0, 1}d, we first transform it into a string S := S(A1, . . . , A2q) by our reduction. By the assumption, this reduction takes T(N) = O(Nd2) time, and nS := |S| ≤ c · Nd2 for some constant c depending on q.
2. Next, we run the algorithm A on S. The running time is
TA(nS) = O(n2q−ϵS) = O(Nd2)2q−ϵ.
Fix the dimension function d(N) := ⌈ (log N)2 ⌉. Since d(N) = ω(log N) holds, the k-OV Hypothesis (with k = 2q) applies also to 2q-OVN, d(N).
By Step 2 we obtain a 2q-OV algorithm with running time :
Ttotal(N) = O(Nd2) + O(Nd2)2q−ϵ = O(Nd2) + ON2q−ϵ · d4q−2ϵ where d = d(N).
Since d = ⌈ (log N)2 ⌉, we have d4q−2ϵ ≤ (log N)2 + 14q−2ϵ = (log N)O(1) = No(1). Thus for any δ > 0 and sufficiently large N,
d4q−2ε ≤ Nδ.
Choose δ = ϵ/2. Then
Ttotal(N) = O(N1+o(1)) + O(N(2q−ϵ)+(ϵ/2)) = O(N2q−ϵ/2),
contradicting the k-OV Hypothesis with k = 2q.
3.3.1 Proof of Lemma 29
To explain our idea, we first give a reduction from 2-OV to 1-REWB matching problem. The reduction can be easily extended to a reduction from 2k-OV to k-REWB.
Lemma 30 (Reduction for k = 1). There exists a (fixed) 1-REWB Ψ1 that solves 2-OV in the following sense: Let N ≥ 1 be an integer and A1, A2 ⊆ {0, 1}d be an instance of 2-OV with |A1| = |A2| = N. There is a string S(A1, A2) such that
S(A1, A2) ∈ L (Ψ1) ⇐⇒ ∃v1 ∈ A1.∃v2 ∈ A2. IP(v1, v2) = 0.
In particular, we can construct S(A1, A2) in O(N · d2) time.
Proof. We note that the proof presented here can be viewed as the REWB-version of a similar result and construction for 1-turn bounded-height (≤ d) pushdown automata [60, Theorem 4].
Let A1 = {v1, v2, . . . , vN} and A2 = {u1, u2, . . . , uN}. We set Σ := {0, 1, #, @, ♮} and define the following string I, which serves as the arena for our construction:
I := # ← − v1 # ← − v2 # · · · # ← − vN #@# u1 # u2 # · · · # uN # ♮
where ← − v means the reversed version of v: i.e., ← − 11001 = 10011. It should be noted that |I| = O(d · N).
A key of our reduction is representing a pair of vectors (vi, uj) with 1 ≤ i, j ≤ N by a single substring of I. A substring π of I represents (vi, uj) if the following holds:
I = · · · # ← − vi π # · · · # @ # · · · # uj # · · · ♮.
More formally, let π = π(i, j) be the factor (substring) of I that starts right after the occurrence of ← − vi and ends right before the occurrence of uj. Explicitly given by:
π(i, j) := (#← − vi+1 # · · · #← − vN ) #@# (u1# · · · #uj−1#)
If i = N, the left part is empty; if j = 1, the right part is empty.
For example, if A1 = {v1 = 011, v2 = 001} and A2 = {u1 = 101, u2 = 100}, then our string I takes the following form:
I = # 110 # 100 # @ # 101 # 100 #♮.
In this setting, the substring π = # 100 # @ # 101 # represents (v1, u2) because I = v1 π w2. Below we write ˜I to denote I for this example.
We define the following building block expression ψ and φ1, φ2 where
• we use ψ by applying it to a copy of I to nondeterministically select and represent vectors v∗ from A1 and u∗ from A2; and
• we use φ1 (resp. φ2) by applying it to a copy of I to check v∗[ℓ] = 0 (resp. u∗[ℓ] = 0) for each index ℓ ∈ [1 .. d].
We first define our expression ψ as follows:
ψ := Γ∗ (# Γ∗ @ Γ∗#)x Γ∗ ♮
where Γ := (0 + 1 + #) is the Regex. We note that Γ cannot consume the symbols @ and ♮.
We apply ψ to I to nondeterministically select vectors v∗ from A1 and u∗ from A2. For our example A1 = {v1 = 011, v2 = 001} and A2 = {u1 = 101, u2 = 100}, applying ψ to ˜I can generate the following match, in which v∗ = v1 and u∗ = u2 are selected:
Γ∗ #110 (#Γ∗@Γ∗#)x #100 #@# 101# Γ∗♮ 100#♮ where x has # 100 #@# 101 #.
Another run can select v∗ = v2 and u∗ = u1 as follows:
Γ∗ # 110 # 100 (#Γ∗@Γ∗#)x #@# Γ∗♮ 101 # 100#♮ . where x has # @ #.
By the above observation, the following is clear.
Proposition 31. Applying ψ to I, it completely consumes I and saves a substring into the variable x, which represents (vi, uj) for some 1 ≤ i, j ≤ N. Moreover, any pair (vi, uj) can be captured and represented via x by applying ψ to I.
Next we define our expressions ϕv and ϕu as follows:
ϕv := Γ∗#B∗ (0 \x B)x B∗#Γ∗ ♮, ϕu := Γ∗#B∗ (B \x 0)x B∗#Γ∗ ♮.
where B := (0 + 1).
The former ϕv requires v∗[ℓ] = 0 and the latter ϕu requires u∗[ℓ] = 0 for some index ℓ ∈ [1 .. d]. For example, applying ϕv to another copy of ˜I under x = #100@#101#, it works as follows:
Γ∗ # # B∗ 11 (0 \x B)x 0 #100 #@# 101# 1 B∗ 00 # # Γ∗♮ ♮ .
This application also updates x as follows:
x = #100 #@# 101# ⇝ 0 #100 #@# 101# 1 .
Since one application of ϕv and ϕu extends x with a single-letter, we can check d ℓ=1(v∗[ℓ] = 0 ∨ u∗[ℓ] = 0) by repeatedly applying the expression (ϕv + ϕu) . For example, applying ϕu to another copy of ˜I under the updated x, it checks if w∗[2] = 0 and updates x as follows:
Γ∗ # # B∗ 1 (B \x 0)x 1 0#100 #@# 101#1 0 B∗ 0 # # Γ∗♮ ♮ , x = 0#100 #@# 101#1 ⇝ 1 0#100 #@# 101#1 0 .
By the above observation, the following is clear.
Proposition 32. Assume the content of x represents vi[ℓ] and uj[ℓ] for some 1 ≤ ℓ ≤ d. Then, applying (ϕv + ϕu) to I, the following holds: if the application succeeds, then vi[ℓ] · uj[ℓ] = 0 and x is updated to represent vi[ℓ + 1] and uj[ℓ + 1] (when ℓ ≤ d).
In summary, we employ the following gadgets:
S(A1, A2) := (1 + d)-copies I I · · · I , Ψ1 := ψ (ϕv + ϕu)∗
It should be noted that the expression Ψ1 does not depend on the instance A1 and A2; this Ψ1 can be used for any 2-OV instances.
By the above argument, it is clear that S(A1, A2) ∈ L (Ψ1) iff there are orthogonal vectors in A1 and A2. We note that |S(A1, A2)| = O(N · d2) because |I| = O(N · d), and S(A1, A2) can be constructed in O(N · d2) time.
We can generalize the above reduction to one from 2k-OV to k-REWB.
Lemma 29. Let k ≥ 1 be an integer. There exists a (fixed) k-REWB Ψk that solves 2k-OV in the following sense: Let N ≥ 1 be an integer and A1, . . . , A2k ⊆ {0, 1}d be an instance of 2k-OV with |A1| = · · · = |A2k| = N. There is a string S(A1, . . . , A2k) such that
S(A1, . . . , A2k) ∈ L (Ψk) ⇐⇒ ∃v1 ∈ A1.∃v2 ∈ A2. · · · .∃v2k ∈ A2k. IP2k(v1, v2, . . . , v2k) = 0.
In particular, we can construct S(A1, . . . , A2k) in O(k · N · d2) time.
Proof. We extend the construction for Lemma 30 to the case k ≥ 2. We represent 2 · k vectors using k variables x1, x2, . . . , xk. We assume the following representation:
A1 = {v11, . . . , v1N}, A2 = {u11, . . . , u1N}, A3 = {v21, . . . , v2N}, A4 = {u21, . . . , u2N}, . . . A2k−1 = {vk1, . . . , vkN}, A2k = {uk1, . . . , ukN}.
We change the definition of I as follows:
I := I1 I2 · · · Ik ,
where
Ir := # ← − vr1 # · · · #← − vrN #@# ur1 # · · · #urN# ♮ .
For example, if k = 2,
I = #← − v11 # · · · #← − v1N #@# u11# · · · #u1n#♮ #← − v21 # · · · #← − v2N @#u21# · · · #u2N#♮ .
We use the variable xr (1 ≤ r ≤ k) to represent (vri, urj) with 1 ≤ i, j ≤ N. For example, if k = 2, we use x1 and x2 as follows:
#← − v11 #← − v12 x1 # · · · #← − v1N #@# u11#u12# · · · #u1N#♮ #← − v21 #← − v22 x2 # · · · #← − v2N #@#u21# u22# · · · #u2N#♮
To accommodate multiple variables, we below modify ψ, ϕv, and ϕu in Lemma 30 (the case k = 1).
We first define ψ to nondeterministically select vectors from A1, A2, . . . , A2k and bind them into x1, . . . xk as follows:
ψ := ψ1ψ2 · · · ψk, where ψr := Γ∗ (#Γ∗@Γ∗#)xr Γ∗♮, Γ := (0 + 1 + #).
As with ψ in Lemma 30, the following holds for ψ.
Proposition 33. Applying ψ to I, it completely consumes I and saves substrings to the variables x1, x2, . . . , xk where each xr represents (vri, urj) for some 1 ≤ i, j ≤ N. Moreover, for each 1 ≤ r ≤ k, any pairs (vri, urj) can be captured and represented via xr by applying ψ to I.
We next define ϕr to check vri[ℓ] = 0 or uri[ℓ] = 0 (1 ≤ ℓ ≤ d) as follows:
ϕr := ϕ1r ϕ2r · · · ϕkr (1 ≤ r ≤ k),
where
ϕsr := ϕs,⊤ (r = s), ϕs,v + ϕs,u (r = s), ϕs,v := Γ∗#B∗ (0 \xs B)xs B∗#Γ∗ ♮ , ϕs,u := Γ∗#B∗ (B \xs 0)xs B∗#Γ∗ ♮ , ϕs,⊤ := Γ∗#B∗ (B\xs B)xs B∗#Γ∗ ♮, B = (0 + 1).
Proposition 34. Assume that, for an index ℓ ∈ [1..d], every xr represents vri[ℓ] and urj[ℓ] for 1 ≤ r ≤ k. If the application of ϕr to I succeeds and consumes I, then either vri[ℓ] = 0 or urj[ℓ] = 0 holds. Moreover, every xr is updated to represent vri[ℓ + 1] and urj[ℓ + 1] (when ℓ ≤ d).
Conversely, if vri[ℓ] = 0 or urj[ℓ] = 0 holds, then applying ϕi to I must succeed.
Using ϕi, we further define ϕ to check the 2k-orthogonality condition:
ϕ := ϕ1 + ϕ2 + · · · + ϕk.
We observe that applying ϕ to I succeeds iff kr=1(vri[ℓ] · urj[ℓ]) = 0 when each xr represents vri[ℓ] and urj[ℓ]. Then, we finally define S(A1, A2, . . . , A2k−1, A2k) and Ψk as follows:
S(A1, A2, . . . , A2k−1, A2k) := (1+d)-copies I I . . . I , Ψk := ψ ϕ∗ .
From the above properties, we observe the following, which completes our proof:
S(A1, A2, . . . , A2k−1, A2k) ∈ L (Ψk) ⇐⇒ the 2k-OV instance contains 2k-orthogonal vectors.
4 Input Normalization
Here, to simplify subsequent arguments, we convert the input to an equivalent, more structured form. Let w be the input string over an alphabet Σ and A, B, C, and D be Regexes.
Let ℓ = ⌈log |Σ|⌉. For each σ ∈ Σ, we assign a unique binary string bin(σ) of length ℓ. Then, we define the string san(w) by replacing each letter σ of w with the string bin(σ) 0 and appending a letter 1 at the end (ℓ + 1) times; that is,
san(w) = bin(w[1]) 0 w[1] bin(w[2]) 0 w[2] · · · bin(w[|w|]) 0 w[|w|] 1ℓ+1.
For example, if Σ = {a, b, c}, w = abacaba, bin(a) = 00, bin(b) = 01, and bin(c) = 10,
san(w) = 00 0 a 01 0 b 00 0 a 10 0 c 00 0 a 01 0 b 00 0 a 111.
Clearly, w consists only of binary letters 0 and 1. Moreover, after the transformation, we have the following, which is the purpose of considering this transformation.
Lemma 35. Let 1 ≤ p < q ≤ |san(w)| − ℓ. Then, san(w)[q .. |san(w)|] is not a prefix of san(w)[p .. |san(w)|].
Proof. Since q ≤ |san(w)| − ℓ, san(w)[q .. |san(w)|] ends with san(w)[|san(w)| − ℓ .. |san(w)|] = 1ℓ+1. However, by definition, san(w) contains no substring of the form 1ℓ+1 other than san(w)[|san(w)| − ℓ .. |san(w)|]. Therefore, san(w)[p .. |san(w)|] cannot contain 1ℓ+1 other than at its end, and thus, cannot have san(w)[q .. |san(w)|] as a prefix.
Moreover, for a Regex E, we define the Regex bin(E) as the Regex obtained by replacing every letter symbol σ occurring in E by the string bin(σ) 0. For example, if Σ = {a, b, c}, E = (a + b)∗(b + c)∗, bin(a) = 00, bin(b) = 01, and bin(c) = 10,
bin(E) = ( 00 0 a + 01 0 b )∗ ( 01 0 b + 10 0 c )∗.
Furthermore, we define
san(A) := bin(A), san(B) := bin(B), san(C) := bin(C), and san(D) := bin(D) 1ℓ+1.
The following lemma is clear from the definition.
Lemma 36. For a Regex E and a string w, L (bin(E)) = {san(w) : w ∈ L (E)}.
The following lemma ensures that this transformation indeed yields an equivalent problem, which is also clear from the definition.
Lemma 37. The following two statements are equivalent.
• w can be decomposed as w = wA wB wC wB wD with wA ∈ L (A), wB ∈ L (B), wC ∈ L (C), and wD ∈ L (D).
• san(w) can be decomposed as san(w) = w′A w′B w′C w′B w′D with w′A ∈ L (san(A)), w′B ∈ L (san(B)), w′C ∈ L (san(C)), and w′D ∈ L (san(D)).
The following lemma is clear from the definition of san(D), but critical for our further use.
Lemma 38. L (san(D)) consists of only strings with length at least ℓ + 1.
Hereafter, throughout this paper, we refer to the string san(w) and the Regexes san(A), san(B), san(C), and san(D) simply as w, A, B, C, and D, respectively. In particular, we assume that Σ is binary and there exists an integer ℓ such that
• for each 1 ≤ p < q ≤ |w| − ℓ, w[q, |w|] is not a prefix of w[p .. |w|] (Lemma 35), and
• L (D) consists only of strings of length at least ℓ + 1 (Lemma 38).
By Lemma 37, this rewriting is an equivalent transformation.
5 Decomposing ABCBD to Two Subproblems
The goal of this section is to decompose the ABCBD problem into the following two subproblems, namely, the XYYZ problem and the branching ABCBD problem.
XYYZ Problem Fixed Objects: Regexes X, Y, and Z. Input: A binary string w. Task: Deciding if we can decompose w into w = wX wY wY wZ so that wX ∈ L (X), wY ∈ L (Y), and wZ ∈ L (Z).
Branching ABCBD Problem Fixed Objects: Regexes A, B, C, and D. Condition on D: Following the argument of Section 4, we assume ϵ / ∈ L (D). Condition on B: Following the argument of Section 5.1, we assume ϵ / ∈ L (B). Input: A binary string w. Task: Deciding if we can decompose w into w = wA wB wC wB wD so that wA ∈ L (A), wB ∈ L (B), wC ∈ L (C), wD ∈ L (D), and • σ = σ′, where σ and σ′ are the first letters that appear immediately after the first and second occurrence of wB in this decomposition, respectively. Let us illustrate the difference between the Branching ABCBD problem and the (vanilla) ABCBD problem with examples. Consider w = 0110110, A = C = Σ∗, and B = D = Σ+ := ΣΣ∗.
Example 1. The decomposition w = 0 wA 11 wB 0 wC 11 wB 0 wD is a feasible decomposition for the vanilla ABCBD problem, but not for the branching version, because the characters appearing immediately after both occurrences of wB are the same letter 0.
Example 2. The decomposition w = 01 wA 1 wB 0 wC 1 wB 10 wD is feasible for both problems, since the character appearing immediately after the first wB is 0 and the character after the second wB is 1.
Example 3. The decomposition w = 0 wA 1 wB ϵ wC 1 wB 0110 wD is also feasible for both problems, since the character appearing immediately after the first wB is 1 and the character after the second wB is 0.
5.1 Removing the empty string ϵ from B
Let A, B, C, and D be classical Regexes (without backreferences) over a finite alphabet Σ. Recall that
L (A (B)x C \x D) = {wAwBwCwBwD : wA ∈ A, wB ∈ B, wC ∈ C, wD ∈ D}.
For the Regex B, by Proposition 13, there exists B−ϵ whose language is L (B) \ {ϵ}.The following trivial case analysis is the first step in our decomposition.
Proposition 39. If ϵ ∈ L (B), we have
L (A (B)x C \x D) = L (A C D) ∪ L (A (B−ϵ)x C \x D) .
Otherwise, we have
L (A (B)x C \x D) = L (A (B−ϵ)x C \x D) .
Since ACD is just a Regex rather than REWB, we can solve the string-matching problem for the expression in linear time. We hereafter focus on the expression A (B−ϵ)x C \x D. From now on, for simplicity, we write B for B−ϵ: i.e., ϵ ∈ L (B).
5.2 The Decomposition
For an ϵ-NFA N = (Q, Σ, ∆, E, q0, F), we define Nq′→F′ as the NFA (Q, Σ, ∆, E, q′, F′) obtained by replacing the initial state of N with q′ and the set of accepting states with F′.
Let NC = (QC, Σ, ∆C, EC, q0C, FC) be a NFA that accepts L (C). We similarly define ND = (QD, Σ, ∆D, ED, q0D, FD). For the main lemma of this section, we define our building block. For states qC ∈ QC and qD ∈ QD of NC and ND, by Proposition 12 , there exists a Regex BqC, qD that satisfies the following:
L (BqC, qD) = L (B) · L Cq0C→{qC} ∩ L Dq0D→{qD} .
We now present the main decomposition lemma of this section.
Lemma 40. Let w be an input string. The following two conditions (1) and (2) are equivalent:
(1) We have w ∈ A (B)x C \x D.
(2) We have either of the following.
XYYZ Case: For some fC ∈ FC and qD ∈ QD, w is matched with the following REWB:
A (BfC, qD)x \x DqD→FD.
Branching Case: For some qC ∈ QC and qD ∈ QD, w is matched with the following REWB:
A (BqC, qD)x CqC→FC \x DqD→FD,
along with the next letter of the substring matched with (BqC, qD)x, σ, and the next letter of the substring matched with \x, σ′, are different (σ = σ′).
Proof. (1) ⇒ (2): We decompose w as w = wAwBwCwBwD where wA ∈ L (A), wB ∈ L (B), wC ∈ L (C), and wD ∈ L (D). Using the longest common prefix v of wC and wD, we can decompose wC and wD as follows:
wC = v w′C, wD = v w′D.
We note that w′D = ϵ holds because of the following reason: From Lemma 38, we have |wD| ≥ ℓ + 1. Therefore, from Lemma 35 and the fact wB = ϵ, wD is not a prefix of the suffix wC wB wD. Thus, we have v = wD, and thus, w′D = ϵ.
Case1: w′C = ϵ. It means that wC = v and w = wA wB wC wB wC w′D wD .
• On the NFA NC, let NC(wC) be the set of possible states after reading wC. NC(wC) contains an accepting state fC ∈ FC because wC ∈ L (C).
• On the NFA ND, let ND(v) be the set of possible states after reading v = wC. Since wD = v w′D ∈ L (D), there is a state qD ∈ ND(v) such that w′D ∈ L DqD→FD.
Since wBwC ∈ L (BfC, qD), we have
w = wA wBwC wBwC w′D ∈ L A (BfC, qD)x \x DqD→FD ,
where wA ∈ L (A), wBwC ∈ L (BfC, qD), and w′D ∈ L DqD→FD. Thus, this case matches the XYYZ case.
Case2: w′C = ϵ. It means that w = wA wB v w′C wC wB v w′D wD . Moreover, from the fact that v is the longest common prefix of wC and wD, the first letters of w′C and w′D are different.
• On the NFA NC, let NC(v) be the set of possible states after reading v. Since wC = v w′C ∈ L (C), there is a state qC ∈ NC(v) such that w′C ∈ L CqC→FC.
• On the NFA ND, let ND(v) be the set of possible states after reading v. Since wD = v w′D ∈ L (D), there is a state qD ∈ ND(v) such that w′D ∈ L DqD→FD.
Then, the string w = wA(wBv)w′C(wBv)w′D matches the following expression:
A (BqC, qD)x (CqC→FC)\x (DqD→FD)
with wBv ∈ L (BqC,qD), w′C ∈ L CqC→FC, and w′D ∈ L DqD→FD. Moreover, in such a matching, the letters that appear immediately after the two substrings wBv are different. Thus, this case matches the branching case.
(2) ⇒ (1):
XYYZ case: Assume
w ∈ L A (BfC,qD)x \x DqD→FD ,
where fC ∈ FC and qD ∈ QD. We decompose w as
w = wAwBwBwD,
where wA ∈ L (A), wB ∈ L (BfC,qD), and wD ∈ L DqD→FD.
By the definition of BfC,qD, we can further decompose wB as wB = w1w2, where w1 ∈ L (B) and w2 ∈ L Cq0C→{fC} ∩ L Dq0D→{qD}. Particularly, w2 ∈ L Cq0C→{fC} ⊆ L (C) and w2 wD ∈ L Dq0D→{qD} · L D{qD}→FD ⊆ L (D). Therefore, we have
w = wA w1 w2 wB w1 w2 wB wD ∈ L (A(B)x C \x D)
with wA ∈ L (A), w1 ∈ L (B), w2 ∈ L (C), and w2wD ∈ L (D).
Branching Case: Assume
w ∈ L A (BqC, qD)x CqC→FC \x DqD→FD ,
where qC ∈ QC and qD ∈ QD is a state of C and D, respectively. We decompose w as
w = wA wB wC wB wD,
where wA ∈ L (A), wB ∈ L (BqC,qD), wC ∈ L CqC→FC, and wD ∈ L DqD→FD.
By the definition of BqC,qD, we can further decompose wB as wB = w1w2, where w1 ∈ L (B) and w2 ∈ L Cq0C→{qC} ∩ L Dq0D→{qD}. Particularly, w2 wC ∈ L Cq0C→{qC} · L C{qC}→FC ⊆ L (C) and w2 wD ∈ L Dq0D→{qD} · L D{qD}→FD ⊆ L (D). Therefore, we have
w = wA w1 w2 wB wC w1 w2 wB wD ∈ L (A(B)x C \x D)
with wA ∈ L (A), w1 ∈ L (B), w2wC ∈ L (C), and w2wD ∈ L (D).
Now, we reduce the ABCBD problem into the XYYZ problem and the branching ABCBD problem. Let w be the given string. If ϵ ∈ B, we check whether w matches the Regex A C D and replace B by B−ϵ. If it matches, we return yes. Otherwise, Lemma 40 ensures that w ∈ A (B)x C \x D if and only if
• w is a yes-instance of the XYYZ problem for X := A, Y := BfC,qD, and Z := DqD→FD for some fC ∈ FC and qD ∈ QD, or
• w is a yes-instance of the branching ABCBD problem for A := A, B := BqC,qD, C := CqC→FC, and D := DqD→FD for some qC ∈ QC and qD ∈ QD.
This algorithm solves the ABCBD problem by calling oracles for the XYYZ problem and the branching ABCBD problem. Moreover, it internally solves the XYYZ problem |FC||QD| times and the branching ABCBD problem |QC||QD| times, both of which are constant. Therefore, we have the following.
Lemma 41. Let f be a function and assume both of the XYYZ problem and the branching ABCBD problem admit O(f(|w|))-time algorithms. Then, the ABCBD problem admits an O(f(|w|))-time algorithm.
6 (X YY Z)-Problem
We first restate our subproblem, the XYYZ problem.
XYYZ Problem Fixed Objects: Regexes X, Y, and Z. Input: A binary string w. Task: Deciding if we can decompose w into w = wX wY wY wZ so that wX ∈ L (X), wY ∈ L (Y), and wZ ∈ L (Z).
6.1 Crochemore’s Maximal Local Power Algorithm
A string x is repetitive or power if it is represented as x = ye for some string y and an integer e ≥ 2. If x is not repetitive, x is primitive.
For example, (1) a string abababab is repetitive because abababab = (ab)4; (2) a string abababa = (ab)3a is primitive.
As in (ab)4 = (abab)2, there may be multiple representations for one repetitive string. For the unique representation, we consider the decomposition by primitive words. More precisely, for a repetitive string x, we denote it as (p, k) where x = pk and p is primitive.
Proposition 42 ([28, Chapter 9]). If a string x is repetitive, there exists just one representation (p, k).
Proof. Since x is repetitive, for some string v, x = vi with i ≥ 2. If v is not primitive, we (repeatedly) decompose v and obtain a primitive factor p such as x = pk . If x = pk = qr held for different primitives p and q, then x = ye for y = x[1..gcd(|p|, |q|)] by Fine and Wilf’s theorem (Lemma 10). Since |p| mod |y| = |q| mod |y| = 0, it contradicts the assumption that p and q are primitives.
Let w be a string. A substring x of w is local power at an index p if x is repetitive and x starts from the index p, x = w[p .. p + |x|). For a primitive θ, 1 ≤ p ≤ |w|, and e ≥ 2, we write (p, θ, e) to denote the local power θe at the index p. A local power (p, θ, e) is (two-sided) maximal if (1) it is not extensible to the left: i.e., w[p − |θ| .. p) = θ or p − |θ| < 1; and (2) it is not extensible to the right: i.e., θ = w[p + e|θ| .. p + (e + 1)|θ|) or p + (e + 1)|θ| > n + 1.
Example. For a string x = aabaabaabba, there are two kinds of maximal powers:
• |θ| = 1: (1, a, 2), (4, a, 2), (7, a, 2), and (9, b, 2).
• |θ| = 3: (1, aab, 3), (2, aba, 2), and (3, baa, 2).
It is worth noting that (4, aab, 2) is a local power but not maximal because it is covered by (1, aab, 3). The following result is shown by Crochemore [27] and plays a critical role in our algorithm.
Theorem 43 ([27],[28, Chapter 9]). Let w be a string and n := |w|. We can compute the set of all maximal local powers of w in O(n log n)-time. The size of this set is also O(n log n).
We show that we can limit the search space for solutions of the XYYZ problem as follows.
Lemma 44. The following conditions are equivalent:
(1) We have a desired decomposition w = x y y z where x ∈ L (X), y ∈ L (Y), and z ∈ L (Z).
(2) There is a maximal local power (p, θ, e) such that
w = w1 θi θj θj θk (p,θ,e) w2, where (w1θi) ∈ L (X) , θj ∈ L (Y) , (θkw2) ∈ L (Z) .
Proof. Trivial Case (2) ⇒ (1): If (2) holds, we just set x := w1θi, y := θj, and z := θkw2.
Case (1) ⇒ (2): Consider a decomposition w = x y y z. Since the string y y is a power, there is a maximal local power (p, θ, e) that covers the substring y y; that is, y = θj for some j and the substring y y begins at the index p + i|θ| for some 0 ≤ i ≤ e − 2j. By taking this maximal local power (p, θ, e) and integers i, j, together with setting k = e − i − 2j, we have x = w1 θi, y = θj, and z = θkw2, where w1 = w[1 .. p) and w2 = w[p + e|θ| .. |w|], respectively.
6.2 Our Tool on Ultimately Periodic Set
The following lemma is fundamental.
Lemma 45. For a finite monoid M and its elements δ and δ′, {i ≥ 0 : δi = δ′} is an ultimately periodic set.
Proof. Consider the sequence (δ0, δ1, . . . ). Since M is finite, there is an element δ′′ that appears at least twice in this sequence. Let δ′′ = δk1 = δk2 for k1 < k2. Then, for k ≥ k2, we have δk = δk−k2δk2 = δk−k2δk1 = δk−(k2−k1). Thus, the set {i ≥ 0 : δi = δ′} is periodic for i ≥ k1.
To give an algorithm for the XYYZ problem, we repeatedly use the following lemma.
Lemma 46. Let E be a Regex, δ ∈ TE, and w1, θ, w2 be strings. Then, {i ≥ 0 : TE(w1 θi w2) = δ} is ultimately periodic. Moreover, the parameters µ and λ of that set are bounded by a constant that depends only on E.
Proof. Let δ1 = TE(w1), δθ = TE(θ), and δ2 = TE(w2). Let D = {δ′ ∈ TE : δ1 ⊙ δ′ ⊙ δ2 = δ}. Then, the desired set is δ′∈D{i ≥ 0 : δiθ = δ′}, which is ultimately periodic because it is the union of a finite number of ultimately periodic sets. Moreover, since that set depends only on transitions δ1, δθ, and δ2, the parameters µ and λ of that set are bounded by a constant that depends only on E.
6.3 Checking each maximal local power in O(1)-time
Using Lemma 44, for a given maximal local power (p, θ, e), we hereafter focus on the problem of whether we can decompose w as
w = w1 θi ∈X θj ∈Y θj ∈Y θk w2 ∈Z i + 2j + k = e,(⋆)
where the prefix w1 = [1 .. p) and the suffix w2 = [p + e|θ| .. |w|] are uniquely determined from (p, θ, e).
To solve the above problem (⋆) in O(1)-time, we introduce some sets of exponents that are candidates of integers i, j, and k. Let
SX := {i ≥ 0 : X(w1 θi) is accepting} = δ∈M(X) δ is accepting {i ≥ 0 : TX(w1 θi) = δ},
SY := {j ≥ 0 : Y(θj) is accepting} = δ∈M(Y) δ is accepting {j ≥ 0 : TY(θj) = δ},
SZ := {k ≥ 0 : Z(θk w2) is accepting} = δ∈M(Z) δ is accepting {k ≥ 0 : TZ(θk w2) = δ},
From Lemmas 14 and 46, all of SX, SY, and SZ are ultimately periodic whose parameters µ and λ are bounded by a constant that depends only on X, Y, and Z, respectively.
Now, we define
S := SX + (2 · SY) + SZ.
From Lemma 14, S is also ultimately periodic whose parameters µ and λ are bounded by a constant that depends only on X, Y, and Z. We have the following.
Lemma 47. There is a way to decompose w as in (⋆) if and only if e ∈ S.
Proof. Assume there is a way to decompose w as in (⋆). Let i, j, and k be the exponents in that decomposition. Since w1 θi, θj, and θk w2 are accepted by X, Y, and Z, respectively, we have i ∈ SX, j ∈ SY, and k ∈ SZ. Thus, from the definition of the Minkowski sum and the 2-multiplication, we have e = i + 2j + k ∈ S.
Conversely, assume e ∈ S. Then, there is a tuple of integers i, j, k with i ∈ SX, j ∈ SY, k ∈ SZ such that i + 2j + k = e. From the definition of SX, SY, and SZ, we have w1 θi ∈ X, θj ∈ Y, and θk w2 ∈ Z. Thus, the lemma is proved.
Clearly, for S = (µ, M, λ, T) and e ≤ |w|, whether e ∈ S or not can be determined in O(µ + λ) = O(1)-time. Moreover, S itself can be computed in constant time from the transitions TX(w1), TX(θ), TY(θ), TZ(θ), and TZ(w2). Furthermore, those transitions can also be computed in constant time using the factorization forest data structure FFX, FFY, and FFZ, which can be constructed in linear time. Thus, with linear time pre-computation, we can answer the problem defined in (⋆) in constant time, which yields the following.
Lemma 48. The XYYZ problem can be solved in O(|w| log |w|) time.
The above discussion still works when we replace the specific constant 2 with any constant integer α ≥ 2. Thus, we have Theorem 9.
Theorem 9. The XYαZ problem admits an O(|w| log |w|)-time algorithm. The hidden constant is 2O(s2) + α · 2O(s), where s := |X| + |Y| + |Z|. Alternatively, at the cost of an additional log |w| factor (i.e., time O(|w| log2 |w|)), we can achieve a polynomial dependence on s + α.
7 Algorithm Overview for the Branching ABCBD Problem
7.1 Notation
Recall that STw is the suffix tree of w. We simply write ST for STw.
Let v be a node of ST. We write Iv for the set of indices of suffix nodes of the subtree rooted at v and it is formally defined as follows:
Iv := {Occ(u) : u ∈ ST[v], isSuffix(u) = 1}.
We also write Hv and Lv for the set of indices of suffix nodes in heavy and light subtrees of v, respectively. More formally, we define Hv and Lv as follows. Let uH (resp. uL) be the child of v where v → uH is a heavy edge (resp. v → uL is a light edge). If there is no such child, we set uH = ⊥ (resp. uL = ⊥). Then, we define
Hv := {Occ(u) : u ∈ ST[uH], isSuffix(u) = 1}, Lv := {Occ(u) : u ∈ ST[uL], isSuffix(u) = 1} ∪ {v} if isSuffix(v) = 1 ∅ otherwise
where we set ST[⊥] = ∅.
Note that v itself is in Lv when v is a suffix node. Moreover, for each non-leaf node v, Iv = Hv ∪ Lv and Hv = HuH ∪ LuH clearly hold.
7.2 From Branching ABCBD to Two Enumeration Problems
In this section, we introduce two subproblems Left-B Transition Enumeration and Right-B Transition Enumeration for decomposing the branching ABCBD problem. We define both of those problems on a heavy-path π of the suffix tree STw, and utilize them to determine whether there is a branching decomposition of w = wA wB wC wB wD such that wB = Γ(v) for some v ∈ π.
We consider the following branching decomposition of w:
w = wA wB wC wB wD,
where wB = Γ(v) for some v ∈ π. We denote mv := |wB|.
Let p and q be the indices of the left ends of the first and the second occurrences of wB: i.e., w[1 .. p) = wA, w[p .. p + mv) = wB, w[p + mv .. q) = wC, w[q .. q + mv) = wB, and w[q + mv .. |w|] = wD. It is clear that p, q ∈ Iv = Hv ∪ Lv. We illustrate this situation as follows:
w = w[1 .. p) wA w[p .. p + mv) wB w[p + mv .. q) wC w[q .. q + mv) wB w[q + mv .. |w|] wD .
Deciding if there is a branching decomposition for a node v of ST, we first check Γ(v) = wB ∈ L (B). This check is done in O(1)-time by using the factorization forest FF and Lemma 18. Then, we consider the following set of candidate transitions of C:
K = {δ ∈ TC : ∃p, q ∈ Iv. K(p, q, δ, mv) ∧ q + mv ≤ |w| ∧ w[p + mv] = w[q + mv]},
where K(p, q, δ, m) is a predicate defined as follows:
K(p, q, δ, m) := w[1 .. p) ∈ L (A) ∧ p + m ≤ q ∧ δ = ∆C( w[p + m .. q) ) ∧ w[q + m .. |w|] ∈ L (D) .
Now, we rephrase our branching ABCBD problem using the above set K.
First, for every node v, the following two conditions are equivalent:
• There is a branching decomposition w = wA wB wC wB wD with wB = Γ(v).
• There is a transition δ in the set K where δ is accepting on C.
This correspondence is clear from our condition on the branching ABCBD problem; that is, we are seeking the decomposition that satisfies the following condition:
• the letters immediately after two occurrences of wB’s are different.
It should be noted that, from the argument of Section 4, we assume ϵ / ∈ L (D).
Next, on a node v, assume δ ∈ K for some accepting transition δ. It means that there exist p and q such that K(p, q, δ, mv) and q + mv ≤ |w| ∧ w[p + mv] = w[q + mv]. Then, it holds that one of {p, q} must belong to the heavy side Hv and the other must belong to the light side Lv. It is confirmed as follows:
• Recall p, q ∈ Iv = Hv ∪ Lv.
• The condition q + mv ≤ |w| ∧ w[p + mv] = w[q + mv] equals the “branching by next letter” condition of the suffix tree.
• Therefore, one of {p, q} must belong to the heavy-side subtree ST[uH] of v and the other must belong to the light-side subtree ST[uL] of v.
Finally, we can compute K by solving the following two enumeration problems:
• Enumerating transitions δ where p is in the heavy side Hv and q is in the light side Lv.
• Enumerating transitions δ where p is in the light side Lv and q is in the heavy side Hv.
More formally, the above two tasks correspond to computing the following two sets:
KL := {δ ∈ TC : ∃p ∈ Hv. ∃q ∈ Lv. K(p, q, δ, mv)}, KR := {δ ∈ TC : ∃p ∈ Lv. ∃q ∈ Hv. K(p, q, δ, mv)}.
For every node v ∈ ST, it is clear that K = KL ∪ KR.
7.3 Left-B and Right-B
According to the discussion in the previous section, we define the following problems:
Left-B Transition Enumeration Fixed Objects: Regexes A, B, C, and D and a string w. Input: A heavy-path π of STw. Task: Compute the union of KL(v) for all v ∈ π. More formally, enumerate all δ ∈ TC such that there is a node v ∈ π, i ∈ Lv, and j ∈ Hv with • j + mv ≤ i, • w[1 .. j) ∈ L (A), Γ(v) ∈ L (B), and w[i + mv .. |w|] ∈ L (D), and • δ = TC( w[j + mv .. i) ). Recall that Γ(v) = w[j .. j + mv) = w[i .. i + mv) holds by definition of mv.
Right-B Transition Enumeration Fixed Objects: Regexes A, B, C, and D and a string w. Input: A heavy-path π of STw. Task: Compute the union of KR(v) for all v ∈ π. More formally, enumerate all δ ∈ TC such that there is a node v ∈ π, i ∈ Lv, and j ∈ Hv with • i + mv ≤ j • w[1 .. i) ∈ L (A), Γ(v) ∈ L (B), and w[j + mv .. |w|] ∈ L (D), and • δ = TC( w[i + mv .. j) ). Recall that Γ(v) = w[i .. i + mv) = w[j .. j + mv) holds by definition of mv.
These problems are identical except for the positional relation; that is, which interval [i, i + mv) or [j, j + mv) corresponding to the string wB is located to the left of the other.
Algorithm 1: Algorithm Overview. 1Procedure branching-ABCBD(w, A, B, C, D) 2Compute the suffix tree STw and its heavy-light decomposition; 3Compute the factorization forests FFA, FFB, FFC, and FFD for A, B, C, and D, respectively; // in O(|w|)-time 4for Heavy-path π of STw do 5KL ←Left-B Transition Enumeration(π, w, A, B, C, D); 6KR ←Right-B Transition Enumeration(π, w, A, B, C, D); 7if There is an accepting transition in KL ∪ KR then 8return yes; 9return no;
The remaining part of this paper concentrates on solving those problems in O(|ST[π]| log |w|) time, where we define ST[π] := ST[u] using the topmost vertex u of π. Using oracles for those problems as sub-routines, we solve the branching ABCBD problem as in Algorithm 1. Our algorithm first computes the suffix tree STw and its heavy-light decomposition, and factorization forests FFA, FFB, FFC, and FFD for further use. Then, for each heavy-path π, we compute the union of all KL and KR using our oracles. Then, the answer is yes if there is an accepting transition in at least one of such KL’s or KR’s. The following lemma proves that, using our oracles, Algorithm 1 correctly solves the branching ABCBD problem efficiently.
Lemma 49. Algorithm 1 solves the branching ABCBD problem for w in O(|w| log2 |w|)-time.
Proof. From above discussion, it is clear that Algorithm 1 correctly solves the branching ABCBD problem. The remaining task is to bound the time complexity.
Computation of the suffix tree, heavy-light decomposition, and factorization forests takes O(|w|)-time. As we will show, Left-B Transition Enumeration and Right-B Transition Enumeration can be solved in O(|ST[π]| log |w|)-time. Moreover, the sum of |ST[π]| over all heavy-paths π is O(|w| log |w|), since the number of vertices in ST is O(|w|) and each vertex of ST belongs to at most O(log |w|) different π’s. Thus, the time complexity of Algorithm 1 is O(|w| log2 |w|).
For both two enumeration problems, we employ a common strategy to solve them: we process v ∈ π in bottom-up order, and for each i ∈ Lv, we efficiently enumerate transitions corresponding to j ∈ Hv that satisfy the conditions using queries to certain data structures. However, the data structures and algorithms for those two problems are different. From the next section, we provide efficient algorithms for those two enumeration problems.
8 Right-B Transition Enumeration
In this section, we solve Right-B Transition Enumeration, while the description of the data structure used internally is postponed to Section 9.
8.1 Overall Strategy
For v ∈ π and i ∈ Lv, we define the set R(v, i) by
R(v, i) := {∆C( w[i + mv .. j) ) : j ∈ Hv, i + mv ≤ j, w[j + mv .. |w|] ∈ L (D)}.
Then, by definition, the desired output for Right-B Transition Enumeration is
v∈π Γ(v)∈L(B) i∈Lv w[1 .. i)∈L(A) R(v, i).
Our algorithm iterates over all v ∈ π in bottom-up order, and then for each v with Γ(v) ∈ L (B), iterates over all i ∈ Lv with w[1 .. i) ∈ L (A) to compute R(v, i), and outputs their union.
Now, we focus on computing R(v, i). The main obstacle here is the constraint w[j + mv .. |w|] ∈ L (D). To tackle this, we partition Hv into the following disjoint sets, which we call bags, indexed by a transition δ of D:
δv := {j ∈ Hv : ∆D( w[j + mv .. |w|] ) = δ}.
Then, Hv can be represented as
Hv = δ∈TD δ v .
Then, we can compute R(v, i) by computing
{∆C( w[i + mv .. j) ) : j ∈ δv, i + mv ≤ j},
for each accepting transition δ of D and taking their union.
8.2 Disjoint-Set Union
Since the partition Hv = δ∈TD δv depends on v, we should update it when we traverse upward along π. Let u be the parent of v. The next task is to compute the partition Hu = δ∈TD δu from the partition Hv = δ∈TD δv.
Let
τ := ∆D( Γ(v)(mu .. mv] ) (= ∆D( Γ(v)[mu + 1 .. mv] ).
Then, τ = ∆D( w[j + mu .. j + mv) ) holds for all j ∈ Hv ∪ Lv = Hu because Γ(v)[1 .. mv] = w[j .. j + mv). (Recall that we employ the 1-origin indexing, w = w[1]w[2] . . . w[|w|].)
Thus, for each δ ∈ TD, we have
δu = {j ∈ Hu : ∆D( w[j + mu .. |w|] ) = δ}
Now, the partition Hu = δ∈TD δu can be computed from Hv = δ∈TD δv as follows: First, for each i ∈ Lv, we add i to the bag ∆D( w[i + mv .. |w|)] )v. Then, δv is updated to the set
{j ∈ Hv ∪ Lv : ∆D( w[j + mv .. |w|] ) = δ}.
Thus, the set δu is obtained by
δ′ : τ⊙δ′=δ δ′ v .
Now, to compute δu, it suffices to merge the bags δ′v. We manage the partition by the following data structure defined as follows, which is similar to the disjoint-union structure in [24, Sec. 21].
Disjoint Set Union (DSU) Data to Manage: Disjoint sets {Bλ}x∈Λ indexed by a label set Λ. Queries: MakeBag(λ): Register a new empty bag Bλ and add λ to Λ. Insert(λ, j): Add an element j to the bag Bλ. Merge(X): Merge all bags Bλ with λ ∈ X into a single bag Bλ∗ with λ∗ ∈ X and return a pair (λ∗, moves), where moves = λ∈X\{λ∗} Bλ. All labels λ in X \ {λ∗} is removed from Λ together with the corresponding Bλ.
If we adopt the small-to-large strategy in Merge(·), it is easy to see that
• MakeBag(·) and Insert(·) queries run in O(1) time, and
• Merge(·) query runs in amortized O(log s) time, where s := |Λ| + | λ∈Λ Bλ|.
8.3 Necessary Queries
The remaining task is to give an algorithm to compute
{∆C( w[i + mv .. j) ) : j ∈ δv, i + mv ≤ j},
for each accepting transition δ. To do this, we define the following data structure, RightEnumerator.
RightEnumerator Depending Global Objects Regex C, the entire string w, and factorization forest of C. Shared Data • A set of indices J. • An index j. method InitializeR(j) : Set w ← [j, |w|] and J ← ∅. method AddR(j) : J ← J ∪ {j}. method GetR(i) : Return the set {∆C( w[i .. j) ) : j ∈ J, i ≤ j}.
We defer to Section 9 the construction of the data structure, which processes InitializeR(j), AddR(j), and GetR(i) in O(1) time.
Algorithm 2: Algorithm Overview for Right-B Transition Enumeration. 1Procedure RightBTransitionEnumeration(π) 2m ← |w|; 3Λ ← ∅; // Set of labels for bags 4Accum ← ∅; 5Initialize DSU; 6foreach v ∈ π in bottom-up (leaf-to-root) order do 7δshrink ← ∆D( w(mv .. m] ); 8m ← mv; 9foreach λ ∈ Λ do 10M[λ] ← δshrink ⊙ M[λ]; 11foreach δ ∈ TD do 12Λδ ← {λ ∈ Λ : M[λ] = δ}; 13if Λδ = ∅ then 14λ∗, moved ← DSU.merge(Λδ); 15foreach j ∈ moved do 16S[λ∗].AddR(j); 17foreach λ ∈ Λδ \ {λ∗} do 18Remove λ from Λ; 19if Γ(v) ∈ L (B) then 20foreach i ∈ Lv with w[1 .. i) ∈ L (A) do 21foreach λ ∈ Λ do 22if M[λ] is an accepting transition of D then 23Accum ← Accum ∪ S[λ].GetR(i + m); 24foreach i ∈ Lv do 25δ ← ∆D( w[i + m .. |w|) ); 26Λδ ← {λ ∈ Λ : M[λ] = δ}; 27if Λδ = ∅ then 28λ ← choose({1, 2, . . . , |TD|} \ Λ); // because |Λ| < |TD| must hold 29DSU.makeBag(λ); 30DSU.insert(λ, i); 31Add λ to Λ; 32M[λ] ← δ; 33S[λ].InitializeR(i); // (Re)initialize our data structure in S[λ] 34else 35λ ← take the unique element of Λδ; 36DSU.insert(λ, i); 37S[λ].AddR(i); 38return Accum;
8.4 Algorithm Description
Our implementation of the algorithm for the Right-B Transition Enumeration is given in Algorithm 2. Algorithm iterates over v ∈ π in bottom-up order while maintaining
• an integer m, which is the length of current string Γ(v),
• a DSU data structure and set Λ of labels, which is initially empty,
• a mapping M from bag labels λ to transitions δ, where M[λ] = δ represents that the bag Bλ in DSU data structure manages the bag δv, and
• RightEnumerator data structure S[λ] for each λ ∈ Λ.
Our algorithm manages the partition using two data structures, DSU and RightEnumerator. More precisely, we manage
• the partition λ∈Λ Bλ = λ∈Λ M[λ]v itself using DSU, and
• for each λ, the bag M[λ]v using the RightEnumerator data structure S[λ] to enables us to use AddR(j) and GetR(j) queries on M[λ]v.
To simulate our equation (♮) for updating, we first update transitions related to bags in the first loop (line 9). Then, we merge the bags designated by DSU.merge(Λδ) in line 14. We also update S[λ∗] and Λ to reflect moves by the merging.
In the block from line 19, we compute the set of adequate transitions corresponding to the case v ∈ π using GetR.
Finally, in the loop defined in line 24, we add each i ∈ Lv to an appropriate bag δ of a label λ with δ = ∆D( w[i + mv .. |w|) ). If such a bag does not exist, the algorithm adds a new bag consisting only of i.
The following lemma explicitly shows our loop invariants, which are somewhat straightforward from above discussion. We give a formal proof for the sake of completeness.
Lemma 50. After merging required by moving to the current v, at the beginning of line 19, the following holds:
(i) {Bλ}λ∈Λ is a partition of Hv.
(ii) For each λ ∈ Λ and j ∈ Bλ, ∆D( w[j + mv .. |w|) ) = M[λ].
(iii) For each δ ∈ TD, there is at most one λ ∈ Λ with M[λ] = δ.
Proof. We prove by induction.
Base Case: When v is the bottom-most vertex of π, the conditions are satisfied because Hv = ∅ and Λ = ∅.
Induction Step: As induction step, consider the step that we move-up to u from v and check the conditions on u. By induction hypothesis, at the beginning of line 19, those three conditions hold for v. The loop from line 24 for v adds {i ∈ Lv : ∆D( w[i + mv .. |w|] ) = M[λ]} to Bλ for each λ. Therefore, after the entire iteration for v (or equivalently, the beginning of the iteration for u), the following holds for every λ ∈ Λ:
Bλ = {j ∈ Hv : ∆D( w[j + mv .. |w|] ) = M[λ]} ∪ {i ∈ Lv : ∆D( w[i + mv .. |w|] ) = M[λ]} = {j ∈ Hu : ∆D( w[j + mv .. |w|] ) = M[λ]},
since u−v is the heavy edge of u and thus Hu = Hv ∪ Lv. It makes the condition (i) satisfied.
In the iteration for u, after processing the loop from line 9, the following holds for every x ∈ X and j ∈ Bλ:
M[λ] = ∆D( w(mu .. mv] ) ⊙ ∆D( w[j + mv .. |w|] ) = ∆D( w[j + mu .. j + mv) ) ⊙ ∆D( w[j + mv .. |w|] ) = ∆D( w[j + mu .. |w|] ),
where the second equality holds from w[1, mv] = w[j, j + mv) for every j ∈ Hu. It makes the condition (ii) satisfied while keeping the condition (i).
Furthermore, for each δ ∈ TC, the loop from line 11 merges all the bags labeled by Λδ. Since this makes condition (iii) satisfied while keeping the conditions (i) and (ii), all the conditions hold for u at the beginning of the loop defined in line 19.
The following lemma proves the correctness of the algorithm.
Lemma 51. Algorithm 2 correctly solves Right-B Transition Enumeration. More precisely, it returns the following set of transitions δ of TC:
δ = ∆C( w[i + mv .. j) ) : v ∈ π, i ∈ Lv, j ∈ Hv, i + mv ≤ j, w[0 .. i) ∈ L (A) , w[i .. i + mv) = w[j .. j + mv) = Γ(v) ∈ L (B) , w[j + mv .. |w|] ∈ L (D) .
Proof. From the definition of GetR(·), line 23 adds transitions δ ∈ TC to Accum if and only if there is a j ∈ Bλ with i + mv ≤ j and ∆C( w[i + mv .. j) ) = δ. This index j satisfies w[j .. j + mv) = w[i .. i + mv) = Γ(v) because j ∈ Hv. It also satisfies w[j + mv .. |w|) ∈ L (MD) because of the condition (ii) of Lemma 50, j ∈ Bλ, and the fact that M[λ] is an accepting transition of D (line 22). Thus, all transitions the algorithm adds to Accum satisfy the condition of this lemma.
Conversely, if a vertex v and indices i and j satisfy the condition of the lemma, the algorithm adds δ = ∆C( w[i + mv .. j) ) to Accum at line 23 at the loop corresponding to v, i, and λ, where λ ∈ Λ is the unique bag label such that j ∈ Bλ, which exists because of condition (i) of Lemma 50.
Time Complexity Analysis. Now we analyze the time complexity. First, we claim the following, which in particular implies that operations iterating over all λ ∈ Λ cost only a constant factor to the time complexity.
Lemma 52. At any moment of the Algorithm 2, we have |Λ| ≤ |TD|.
Proof. |Λ| only increases at line 31. From condition (iii) of Lemma 50 and the criterion of line 27, after adding a bag label to Λ, the value (transition) M[λ] differs for all different labels λ. Thus, we have |Λ| ≤ |TD|.
On the assumption that the Right-Enumeration data structure answers each query in constant time, the following holds.
Lemma 53. The time complexity of Algorithm 2 is bounded by O(N log N) where N = |ST[π]|. (Recall that ST[π] := ST[u] for the topmost vertex of π.)
Proof. We bound the total number of queries on RightEnumerator data structure the algorithm calls, which are the bottleneck of our algorithm.
Loop of line 11. Since we call AddR(j) for j ∈ moved obtained by DSU.merge, the total number of AddR called by this loop is bound by the total number of moving throughout merging bags. Such number is clearly bound by O(N log N) due to the two facts that 1) the total number of elements managed by DSU is bounded by N; 2) each element is moved at most log N times due to the small-to-large merging.
Loop of line 19. We call GetR queries at most |Λ| ≤ |TD| times for each i ∈ Lv. Thus, the number of GetR queries in the algorithm is |TD| times the sum of |Lv| for all v ∈ π, which is |TD| · N ≤ O(N).
Loop of line 24. The total number of AddR called by this loop is bounded by v∈π |Lv| = N.
These arguments show that the time complexity of Algorithm 2 is bounded by O(N log N).
9 Data Structure for Right-B Transition Enumeration
In this section, we give an implementation of the RightEnumerator data structure that processes InitializeR, AddR, and GetR in constant time. For the sake of readability, we here restate the function of RightEnumerator.
RightEnumerator Depending Global Objects Regex C, the entire string w, and factorization forest of C. Shared Data • A set of indices J. • An index j. method InitializeR(j) : Set w ← [j, |w|] and J ← ∅. method AddR(j) : J ← J ∪ {j}. method GetR(i) : Return the set {∆C( w[i .. j) ) : j ∈ J, i ≤ j}.
For each node f of the factorization forest, we denote the corresponding interval by [ℓv, rv). Moreover, if f is an idempotent node, we denote the corresponding transition by ef.
9.1 Our Ideas for RightEnumerator
Our Basic Idea. Our data structure utilizes the factorization forest FFC,w (or simply FF) on the transition monoid TC and the string w, and maintains a set J of indices of w. Our main strategy towards processing queries in constant time is to maintain the following set of transitions for each node f ∈ FF:
Df := {∆C( w[ℓf .. j) ) : j ∈ J, j ∈ [ℓf, rf)}.
Consider answering GetR(i) query using Df. Let Xi be the set of nodes such that the (disjoint) union of intervals [ℓf, rf) over all f ∈ Xi is [i, |w|]: i.e., [i, |w|] = f∈Xi[ℓf, rf).
Then, the set of transitions that GetR(i) should return can be written as follows:
{∆C( w[i .. j) ) : j ∈ J, i ≤ j} = f∈Xi{∆C( w[i .. j) ) : j ∈ J, j ∈ [ℓf, rf)} = f∈Xi{∆C( w[i .. ℓf) ) ⊙ ∆C( w[ℓf .. j) ) : j ∈ J, j ∈ [ℓf, rf)} = f∈Xi{∆C( w[i .. ℓf) ) ⊙ δ : δ ∈ Df} = f∈Xi ∆C( w[i .. ℓf) ) ⊙ Df
which can be computed just by iterating each f ∈ Xi.
By the identity above, the target set can be obtained simply by iterating over the elements of Xi. Hence, we need to have a small family Xi that exactly covers the suffix interval [i .. |w|]. Using the famous segment tree instead of the factorization forest yields such family Xi with |Xi| = O(log |w|), which is from the fact that the segment tree on a |w|-length array has a height O(log |w|). This yields the desired RightEnumerator data structure that processes each query in O(log |w|) time, which is suitable for our purpose if we allow an additional logarithmic factor on the time complexity of the whole algorithm.
For further acceleration, we employ the factorization forest, which has a constant height. The issue here is that, since some of the idempotent nodes may have an unbounded number of children, the size of Xi is unbounded. For example, consider the following factorization forest:
In this case, Xi should have size |w| − i + 1 = O(|w|) because we cannot use any of the non-leaf nodes to exactly cover [i .. |w|]. Thus, we cannot directly iterate over all f ∈ Xi for the query GetR(i).
Using Idempotency. The idea here is to process simultaneously almost all f ∈ Xi that are children of the same idempotent node. Let g be an idempotent node with i ∈ [ℓg, rg), and let f1, . . . , fp, . . . , fq be the children of g in that order, where Xi contains fp, . . . , fq 6. Let eg be the idempotent transition corresponding to the node g; i.e., ∆C( w[ℓft, rft) ) = eg for all t ∈ {1, . . . , q}. We simultaneously process fp+1, . . . , fq ∈ Xi using the following observation.
6Since Xi covers [i .. |w|], if fp ∈ Xi, then fp′ ∈ Xi for every p′ > p.
Lemma 54. We have
q t=p+1 ∆C( w[i .. ℓft) ) ⊙ Dft = ∆C( w[i .. ℓfp) ) ⊙ q t=p+1 (eg ⊙ Dft) .
Proof. We have the following equation:
q t=p+1 ∆C( w[i .. ℓft) ) ⊙ Dft
The remaining task is to compute the set q t=p+1 (eg ⊙ Dft) efficiently. To do so, we define the following maxidx:
maxidxg[δ] := max{t : 1 ≤ t ≤ q, δ ∈ eg ⊙ Dft}.
where we define the max of the empty set is −∞: i.e., max ∅ = −∞. Then, we have the following.
Lemma 55. We have
q t=p+1 (eg ⊙ Dft) = {δ : δ ∈ TC, maxidxg[δ] > p}.
Proof. (⊆): Assume δ ∈ q t=p+1 (eg ⊙ Dft) and let t be an index with δ ∈ eg ⊙ Dft. Then, we have maxidxg[δ] ≥ t > p.
(⊇): Assume t := maxidxg[δ] > p. Then, δ ∈ eg ⊙ Dft ⊆ q t=p+1 (eg ⊙ Dft).
Combining Lemmas 54 and 55 immediately yields the following.
Lemma 56. We have
q t=p+1 ∆C( w[i .. ℓft) ) ⊙ Dft = {∆C( w[i .. ℓfp) ) ⊙ δ : δ ∈ TC, maxidxg[δ] > p}.
Using maxidx, the right hand side of the formula on Lemma 56 can be computed just by iterating over all δ ∈ TC. Thus, we can compute the desired left hand side in constant time.
9.2 Implementation of RightEnumerator
Remark. To simplify our pseudocodes, we use class or module features supported by many programming languages. We employ the object-oriented (Java) style; see Sections 1.1 and 1.2 of [98]. Particularly, in this section, we write
• S.add(x) for the operation of adding the element x to the set S,
• f.parent to represent the parent of the node f,
• g.numOfChildren to represent the number of children of the node g,
• g.childOf(p) to represent the p-th child (from the left) of the node g (1-origin), and
• g.childIdx(f) to represent, for two nodes f and g with g = f.parent, an integer p such that f is the p-th child of g (from the left).
The Implementation. Our data structure is given in Algorithm 3, which manages the sets Df for each node f and the value maxidxg[δ] for each idempotent node g and δ ∈ TC.
The constructor InitializeR initializes Df and maxidxg[δ], which seems to consume O(|w|) time. This issue can be bypassed as follows. Instead of initializing all nodes at once at the beginning, we create and initialize each node only when the data structure first accesses it. Then, InitializeR(·) can be implemented to work in constant time without affecting the time complexity of other procedures.
Algorithm 3: Implementation of the Right-Enumeration Data Structure. 1method InitializeR(EC, F) Input: A Regex C and its factorization forest FF, both are given by references or pointers 2Df ← ∅ for each node f of FF; 3maxidxg[δ] ← −∞ for each idempotent node g of FF and δ ∈ TC; 4method AddR(j) Input: j ∈ [|w|] 5f ← the leaf node of FF corresponding to the index j; 6while f is not root do 7g ← f.parent; 8δ ← ∆C( w[ℓf .. j) ); 9Df.add(δ); 10if g is an idempotent node then 11p ← g.childIdx(f) ; // f is p-th child of g 12maxidxg[eg ⊙ δ] ← max(p, maxidxg[eg ⊙ δ]); 13f ← g ; // move up the factorization forest 14method GetR(i) Input: i ∈ [|w|] 15f ← the leaf node corresponding to the index i; 16Accum ← Df; 17while f is not root do 18g ← f.parent; 19p ← g.childIdx(f) ; // f is the p-th child of g 20if p < g.numOfChildren then // f is not the rightmost child of g 21f+ ← g.childOf(p + 1) ; // f+ is the immediate right sibling of f 22foreach δ ∈ Df+ do 23Accum.add(∆C( w[i .. ℓf+) ) ⊙ δ); 24if g is an idempotent node then 25foreach δ ∈ TC do 26if p + 1 < maxidxg[δ] then 27Accum.add(∆C( w[i .. ℓf+) ) ⊙ δ); 28f ← g ; // move up the factorization forest 29return Accum;
Now we prove the correctness of our implementation. The following lemma ensures that the procedure AddR correctly updates Df.
Lemma 57. Let j ∈ [|w|]. Then, the query AddR(j) adds ∆C( w[ℓf .. j) ) to Df for all nodes f with j ∈ [ℓf, rf) (and only for those nodes).
Proof. The loop defined in line 6 iterates over all nodes f with j ∈ [ℓf, rf). For each of such f, line 9 adds the transition ∆C( w[ℓf .. j) ) to Df.
Thus, we have the following, which is immediate from Lemma 57.
Lemma 58. Let J be a set of indices. Assume we have invoked AddR(j) once for each j ∈ J, in any order. Then, for every node f, Df = {∆C( w[ℓf .. j) ) : j ∈ J, j ∈ [ℓf, rf)}.
We now ensure that the method AddR correctly updates maxidxg[δ] by the following lemma.
Lemma 59. Let j ∈ [|w|]. Then, the query AddR(j) updates maxidxg[δ] by max(p, maxidxg[δ]) for all idempotent node g with j ∈ [ℓg, rg), where
• δ = eg ⊙ ∆C( w[ℓf .. j) ), where f is the unique child of g with j ∈ [ℓf, rf), and
• p is the integer such that f is the p-th child of g,
and does not update other idempotent nodes.
Proof. The loop of line 6 iterates over all (g, f) satisfying the condition of the lemma, and line 12 is processed when and only when g is idempotent, f is the p-th child of g, and eg ⊙ δ = eg ⊙ ∆C( w[ℓf .. j) ).
Now, we have the following.
Lemma 60. Let J be a set of indices. Assume we have invoked AddR(j) once for each j ∈ J, in any order. Then, for each idempotent node g and δ ∈ TC, we have
maxidxg[δ] = max{t : 1 ≤ t ≤ q, δ ∈ eg ⊙ Dft}.
where q is the number of children of g and ft is the t-th child of g.
Proof. From Lemma 59, maxidxg[δ] is equal to the maximum among integers t such that there is an index j ∈ J with
• j ∈ [ℓft, rft) ⊆ [ℓg, rg), where ft is the t-th child of g, and
• δ = eg ⊙ ∆C( w[ℓft .. j) ).
From Lemma 58, we have
{eg ⊙ ∆C( w[ℓft .. j) ) : j ∈ J ∩ [ℓft, rft)} = eg ⊙ Dft.
Thus, we have
maxidxg[δ] = max{t : 1 ≤ t ≤ q, ∃j ∈ J ∩ [ℓft, rft), δ = eg ⊙ ∆C( w[ℓft .. j) )}
The following lemma proves the correctness of the implementation of the method GetR in Algorithm 2.
Lemma 61. Let i ∈ [|w|]. Then, GetR(i) returns the set {∆C( w[i .. j) ) : j ∈ J, i ≤ j}.
Proof. GetR(i) returns the union of
(i) Df for the leaf node f corresponding to the index i (line 16),
(ii) ∆C( w[i .. ℓf+) ) ⊙ Df+ for each node f with i ∈ [ℓf, rf) that is not the rightmost child of the parent of f, where f+ is the immediate right sibling of f (line 23), and
(iii) {∆C( w[i .. ℓf+) ) ⊙ δ : δ ∈ TC, maxidxg[δ] > p + 1} for each node f with i ∈ [ℓf, rf) that is the non-rightmost p-th child of an idempotent node g, where f+ is the immediate right sibling of f, (p + 1)-th child of g (line 27).
From now on, we rewrite these sets in a more manageable form.
(i). We have
Df = {∆C( w[ℓf .. j) ) : j ∈ J ∩ [ℓf, rf)} = {∆C( w[i .. j) ) : j ∈ J, j = i}
where the first equality is from Lemma 58 and the second equality follows from [ℓf, rf) = {i}.
(ii). For each node f satisfying the condition of (ii), we have
∆C( w[i .. ℓf+) ) ⊙ Df+ = {∆C( w[i .. ℓf+) ) ⊙ ∆C( w[ℓf+ .. j) ) : j ∈ J ∩ [ℓf+, rf+)}
where the first equality is from Lemma 58.
(iii). Let g be an idempotent node and f1, . . . , fp = f, fp+1 = f+, . . . , fq be its children such that i ∈ [ℓf, rf). Since Lemma 60 ensures that maxidxg is correctly computed, we can apply Lemma 56 to obtain
{∆C( w[i .. ℓf+) ) ⊙ δ : δ ∈ TC, maxidxg[δ] > p + 1}
Now, it suffices to prove that the union of intervals
(I) consisting only of an index i,
(II) [ℓf+, rf+) for each pair of nodes (f, f+) defined in (ii), and
(III) [rf+, rg) for each tuple of nodes (g, f, f+) defined in (iii)
coincides with the interval [i .. |w|].
(⊆ [i .. |w|]): Clearly, each interval is included in [i .. |w|].
(⊇ [i .. |w|]): We prove that for each j ∈ [i .. |w|], j is in one of such intervals. Let g be the lowest node of the factorization forest such that i, j ∈ [ℓg, rg).
If g is a leaf node, we have i = j and the interval (I) contains j. Otherwise, let f and f′ be the children of g such that i ∈ [ℓf, rf) and j ∈ [ℓf′, rf′). Since g is the lowest node with i, j ∈ [ℓg, rg), we have f = f′. Let f+ be the node immediately at the right of f.
If f′ = f+, the interval [ℓf+, rf+) in (II) for the pair (f, f+) contains j. Otherwise, g has at least three children, and thus, is an idempotent node. Thus, the interval [rf+, rg) in (III) for the tuple (g, f, f+) contains j. Therefore, the union of the intervals defined in (I), (II), and (III) coincides with [i .. |w|] and the lemma is proved.
Clearly, each query in Algorithm 3 runs in time proportional to the height of the factorization forest and |TC|, both of which are constants. Therefore, each query runs in constant time, and thus, Algorithm 3 is an implementation of Right-Enumeration data structure with the desired property.
10 Algorithm Overview for Left-B Transition Enumeration
10.1 Overall Strategy
Here, we solve Left-B Transition Enumeration on a heavy-path π of the suffix tree STw of w in O(|ST[π]| log |w|)-time. Our algorithm iterates over v ∈ π in bottom-up order, and for each v with Γ(v) ∈ L (B), computes the following set of transitions for each i ∈ Lv such that w[i + mv .. |w|] ∈ L (D):
Dleft := {∆C( w[j + mv .. i) ) : j ∈ Hv, w[1 .. j) ∈ L (A) , j + mv ≤ i}
where mv = |Γ(v)| is the length of the associated string Γ(v) of the vertex v.
To compute Dleft in O(log |w|)-time, we use a data structure, LeftEnumerator, defined on the ex C and the suffix w corresponding to the heavy-path π. It provides queries InitializeL(·), AddL(·), ShrinkL(·), and GetL(·) defined as follows.
LeftEnumerator Depending Global Data Regex C, the entire string w, and factorization forest of C. Shared Data • a set of indices J • a suffix w • a non-negative integer m Providing the following queries: InitializeL(j) : Set w ← w[j .. |w|] and m ← n − j. AddL(j) : J ← J ∪ {j}. It is guaranteed that w[j .. j + m) is a prefix of w. ShrinkL(d) : Set m ← m − d. It is guaranteed that d ≥ 0. GetL(i) : Return the set {∆C( w[j + m .. i) ) : j ∈ J, j + m ≤ i}.
Algorithm 4: Algorithm Overview for Left-B Transition Enumeration 1Procedure LeftBTransitionEnumeration(π) 2enumerator ← LeftEnumerator; 3enumerator.InitializeL(j), where j is the index corresponding to the leaf of π; 4Accum ← ∅; 5foreach v ∈ π in bottom-up order do 6mv ← |Γ(v)|; 7enumerator.ShrinkL(m − mv); 8if Γ(v) ∈ L (B) then // this check is in O(1) time using the factorization forest. 9foreach i ∈ Lv do 10if w[i + mv .. |w|] ∈ L (D) then 11D ← enumerator.GetL(i); 12Accum ← Accum ∪ D; 13foreach i ∈ Lv with w[1 .. i) ∈ L (A) do 14enumerator.AddL(i); 15return Accum;
We defer the implementation details of data structure LeftEnumerator, which processes each query in amortized O(log |w|) time, to the subsequent sections. We now present our algorithm for Left-B Transition Enumeration, as shown in Algorithm 4. As noted earlier 7.3, we begin by J = ∅ and iterate over v ∈ π in bottom-up order. For each v ∈ π, we apply the following operations.
• First, we set m ← mv using a ShrinkL(·) query (line 7).
• Then, assuming wv ∈ L (B), for each i ∈ Lv with w[i + m .. |w|] ∈ L (D), we compute the set {∆C( w[j + m .. i) ) : j ∈ J, j + m ≤ i} by calling GetL(i) (line 11).
• Finally, we properly update J by adding each i ∈ Lv with w[1 .. i) ∈ L (A) by calling AddL(i) (line 14).
The following lemma ensures that the algorithm correctly updates the set J.
Lemma 62 (Loop Invariant). Every visiting the line 5 of Algorithm 4, the following holds:
enumerator.J = {j ∈ Hv : w[1 .. j) ∈ L (A)}.
Proof. We prove by induction. If v is the leaf of π, the statement is immediate from enumerator.J = Hv = ∅. Otherwise, let u be the child of v on π. Since Hv = Hu ∪ Lu, we have
{j ∈ Hv : w[1 .. j) ∈ L (A)} = {j ∈ Hu : w[1 .. j) ∈ L (A)} ∪ {j ∈ Lv : w[1 .. j) ∈ L (A)}.
By induction hypothesis, the first term of the right-hand side was equal to enumerator.J at the beginning of the loop for u. The second term of the right-hand side is exactly the set that was added to enumerator.J while the loop for u in line 14. Thus, the lemma is proved.
The following lemma ensures the correctness of Algorithm 4.
Lemma 63. Algorithm 4 correctly solves Left-B Transition Enumeration. More precisely, it returns the following set of transitions δ of TC:
δ = ∆C( w[j + mv .. i) ) : v ∈ π, i ∈ Lv, j ∈ Hv, j + mv ≤ i, w[0 .. j) ∈ L (A) , w[j .. j + mv) = w[i .. i + mv) = Γ(v) ∈ L (B) , w[i + mv .. |w|] ∈ L (D) .
Proof. From the definition of GetL(·), line 11 adds transitions δ ∈ TC to Accum if and only if there is a j ∈ J with j + mv ≤ i and ∆C( w[j + mv .. i) ) = δ. By Lemma 62, j satisfies w[1 .. j) ∈ L (A) and j ∈ Hv. Moreover, we have w[j .. j + mv) = w[i .. i + mv) = Γ(v) because j ∈ Hv. Line 10 ensures w[i + mv .. |w|] ∈ L (D). Thus, all transitions the algorithm adds to Accum satisfy the condition of this lemma.
Conversely, if a vertex v and indices i and j satisfy the condition of the lemma, the algorithm adds δ = ∆C( w[j + mv .. i) ) to Accum at line 11 at the loop corresponding to v and i.
Time Complexity of Algorithm 4. Now we analyze the time complexity. It is clear that Algorithm 4 calls O(|ST[π]|) number of queries. Thus, using an implementation of the Left-Enumeration data structure that processes each of four types of queries in (amortized) O(log |w|) time, we can bound the time complexity of Algorithm 4 by O(|ST[π]| log |w|).
10.2 Data Structure Overview for LeftEnumerator
To solve Left-B Transition Enumeration, it suffices to implement LeftEnumerator. Unfortunately, it does not seem easy to realize this data structure just by using factorization forests as we did in Section 9, due to the presence of the ShrinkL(·) queries.
To this end, we consider an auxiliary data structure, AuxiliaryEnumerator, that efficiently processes queries that are somewhat weaker than our purpose. Then, we construct LeftEnumerator using AuxiliaryEnumerator. The precise definition of AuxiliaryEnumerator is as follows.
AuxiliaryEnumerator Depending Global Data Regex C, the entire string w, and factorization forest of C. Shared Data • a set of intervals J = {[j1, k1), [j2, k2), . . .} • a suffix w • a non-negative integer m Providing the following queries or methods: InitializeA(j) : Set w ← [j, n) and m ← n − j. AddA(j, k) : J ← J ∪ {[j, k)}. It is guaranteed that j + m ≤ k and w[j .. k) is a prefix of w. ShrinkA(d) : Set m ← m − d. It is guaranteed that d ≥ 0. GetA(i) : Return the set {TC( w[j + m .. i) ) : [j, k) ∈ J, k ≤ i}.
Here, we explain how AuxiliaryEnumerator differs from LeftEnumerator.
First Difference: Interval. The first difference is that, whereas LeftEnumerator maintains a set of indices J, the auxiliary data structure AuxiliaryEnumerator maintains a set of intervals J. Due to this difference, the AddA(j, k) query takes an additional argument k ≥ j + m compared to the AddL(j) query, where k is the index of the right endpoint of the interval. Note that each interval [j, k) ∈ J always satisfies j + m ≤ k, since this condition holds when that interval is added to J and m never increases thereafter.
Second Difference: Outputs of Get queries. The second difference is what Get(·) queries return. Recall that GetL(i) returns:
{∆C( w[j + m .. i) ) : j ∈ J, j + m ≤ i}.
On the other hand, GetA(i) returns:
{∆C( w[j + m .. i) ) : [j, k) ∈ J, k ≤ i}.
Using the notation
JL := {j ∈ J : j + m ≤ i}, JA := {j : [j, k) ∈ J, k ≤ i},
we can write
GetL(i) = {∆C( w[j + m .. i) ) : j ∈ JL}, GetA(i) = {∆C( w[j + m .. i) ) : j ∈ JA}.
The definition of JL depends on m, so whether j ∈ JL may change as a result of ShrinkL queries. On the other hand, the definition of JA does not depend on m, and thus whether [j, k) ∈ JA remains invariant by ShrinkL queries. This is the main reason we work with GetA(·) instead of GetL(·); GetA(·) is easier to compute.
Simulating GetL(i) using GetA(i). The remaining part of this section focuses on how to simulate LeftEnumerator using AuxiliaryEnumerator. To do so, we need to simulate GetL(·) using GetA(·). In our construction, we manage the following condition:
J = {j : [j, k) ∈ J}.
Particularly, since j + m ≤ k holds for all [j, k) ∈ J, we have JA ⊆ JL. Therefore, the remaining task is to compute
Getnear(i) := {∆C( w[j + m .. i) ) : j ∈ Jnear}
for some Jnear with JL \ JA ⊆ Jnear ⊆ JL. Then, we can compute GetL(i) by
GetL(i) = GetA(i) ∪ Getnear(i).
We note that the definition of Jnear has some flexibility; particularly, it may have non-empty intersection with JA. Here, we adopt the definition
Jnear := {j ∈ J : j + m ≤ i < j + 2m}.
Clearly, we have Jnear ⊆ JL.
Let
k∗j := min k : [j,k)∈J k.
Then, if we have k∗j ≤ j + 2m for all j ∈ J, we have
JL \ JA = {j : j ∈ J : j + m ≤ i < k∗j} ⊆ {j : j ∈ J : j + m ≤ i < j + 2m} = Jnear.
Thus, the remaining tasks are:
(i) implementing AuxiliaryEnumerator,
(ii) implementing Getnear(·), and
(iii) ensuring that k∗j ≤ j + 2m holds for every moment of the algorithm.
Here, we focus on (iii) and defer (i) and (ii) to Section 11 and Section 12, respectively.
Ensuring (iii). The issue in ensuring (iii) is that ShrinkA(·) may cause (iii) to fail by decreasing m. We overcome this issue by the following idea: if ShrinkA(·) breaks (iii) for some j ∈ J, then we update k∗j to j + m by adding to J the interval [j, j + m) using new m.
Note that this re-registration scheme clearly preserves the condition
J = {j : [j, k) ∈ J}
because we add [j, k) to J only when j ∈ J. Moreover, once a ShrinkA(·) query updates k∗j := j + m by calling AddA(j, j + m), next update will happen only after m is halved; it requires the condition j + 2m < k∗j. Thus, we call at most O(log |w|) AddA(·) queries in total for each call of AddL(·) query, and particularly, the re-registration scheme costs O(log |w|) to the total time complexity.
Algorithm 5: Implementation of LeftEnumerator Using the Auxiliary Data Structure AuxiliaryEnumerator 1Class LeftEnumerator: 2Global Data 3w: entire input string; 4(Shared) Data 5m: non-negative integer; 6j: the starting index of the suffix; 7Q: a queue; 8aux: AuxiliaryEnumerator; 9method InitializeL(j) Input: j ∈ [|w|] 10Initialize j; 11aux ← InitializeL(j); 12Q ← empty queue; 13method AddL(j) Input: j ∈ [|w|] such that w[j .. j + m) is a prefix of w = w[j .. |w|] 14aux.AddA(j, j + m); 15if m > 0 then 16Q.pushBack((j, m)); // add (j, m) to the end of Q 17method ShrinkL(d) Input: d ∈ [m] 18m ← m − d; 19while Q is not empty do 20(j, m′) ← Q.front(); // load the first element of Q 21if 2m < m′ then 22Q.popFront(); // remove the first element (= (j, m′)) from Q 23aux.AddA(j, j + m); 24if m > 0 then 25Q.pushBack((j, m)); 26else 27break; 28method GetL(i) Input: i ∈ [|w|] 29D1 ← aux.GetA(i); 30D2 ← GetNearTransitions(i, m); 31return D1 ∪ D2;
10.3 Implementing LeftEnumerator using AuxiliaryEnumerator
Implementation. Here, we formally implement the idea in Section 10.2. Our implementation is given in Algorithm 5. It internally uses AuxiliaryEnumerator and a procedure GetNearTransitions(i, m), which computes the set Getnear(i) for current m. To manage the “re-registered” AddA(·) queries, we use a queue Q. As in Section 9, we use class or module features in our pseudocode. Specifically, we write
• Q.pushBack(x) for the operation of adding x to the last of the queue Q,
• Q.popFront() for the operation of removing the first element of the queue Q, and
• Q.front() for the first element of the queue Q.
Correctness proof. The following lemma is straightforward and specifies our invariants.
Lemma 64. Let J be a set of indices. Assume we have invoked
• InitializeL(·) once at the beginning,
• AddL(j) once for each j ∈ J in any order, and
• ShrinkL(·) and GetL(·) for any number of times.
Let J be the set of intervals [j, k) that AddA(j, k) is called. Then, at any moment, we have the following.
(i) J = {j : [j, k) ∈ J}.
(ii) j + m ≤ k∗j ≤ j + 2m holds for each j ∈ J, where k∗j = mink : [j,k)∈J k.
(iii) If m = 0, we have Q = ∅. Otherwise, J = {j : (j, m′) ∈ Q}.
(iv) Every pair (j, m′) ∈ Q satisfies m ≤ m′ < 2m.
(v) The second elements of Q is non-increasing: i.e., m1 ≥ m2 ≥ · · · ≥ m|Q| for Q = [(j1, m1), (j2, m2), . . . , (j|Q|, m|Q|)]
Proof. We prove by induction. Since InitializeL(·) sets J = J = Q = ∅, at the beginning of the algorithm, the conditions hold. For the remaining three methods, we assume that the conditions are satisfied before they are invoked, and we show that they remain satisfied after the execution.
GetL(·). All conditions are clearly preserved because GetL(·) updates no data.
AddL(j). The conditions (i) and (ii) are preserved because AddL(j) just adds j to J and [j, j + m) to J without updating m. The conditions (iii) and (iv) are preserved because Q is not updated when m = 0 and (j, m) is added to Q when m > 0. The condition (v) is preserved because of the facts that m|Q| ≥ m held before processing the query, which is from the condition (iv) of the induction hypothesis, and (j, m) is added to the last of Q.
ShrinkL(d). The condition (i) is preserved because ShrinkL(d) adds an interval [j, j + m) to J only when (j, m′) was already in Q for some m′, which ensures j ∈ J because of the condition (iii) of the induction hypothesis. For the remaining conditions, we branch into two cases: whether m becomes 0 at line 18 or not.
m becomes 0. From the condition (iii) of the induction hypothesis, we have J = {j : (j, m′) ∈ Q} before processing the query. Moreover, from the condition (iv) of the induction hypothesis, the condition 0 = 2m < m′ at line 21 holds for all (j, m′) ∈ Q. Thus, the method adds [j, j) to J and sets k∗j = j for all j ∈ J, which makes the condition (ii) satisfied. Moreover, the method removes all elements of Q and adds no element to Q, which makes the conditions (iii), (iv), and (v) satisfied.
m remains positive. From the condition (v) of the induction hypothesis, the condition 2m < m′ at line 21 holds for an initial segment of Q (in order from the front), and is not satisfied for the remaining elements. Thus, the method removes all elements (j, m′) with 2m < m′ from Q and instead adds (j, m) at the last of Q. That is, using the largest index x of Q with 2m < mx, Q becomes
Q = [(jx+1, mx+1), . . . (j|Q|, m|Q|), (j1, m), (j2, m), . . . , (jx, m)].
This sets k∗j := m for each j ∈ {j1, . . . , jx}, which makes the condition (ii) satisfied. The condition (iii) is preserved because the set {j : (j, m′) ∈ Q} does not change. The condition (iv) is clear from the definition of x. The condition (v) is from mx+1 ≥ · · · ≥ m|Q| ≥ m, which is from the conditions (iv) and (v) of the induction hypothesis.
Now, we prove the correctness of Algorithm 5.
Lemma 65. GetL(i) returns the following set of transitions:
{∆C( w[j + m .. i) ) : j ∈ J, j + m ≤ i}.
Proof. From the condition (i) of Lemma 64, we have
GetA(i) = {∆C( w[j + m .. i) ) : [j, k) ∈ J, k ≤ i} = ∆C( w[j + m .. i) ) : j ∈ J, k∗j ≤ i .
Moreover, from the condition (ii) of Lemma 64, we have
{∆C( w[j + m .. i) ) : j ∈ J, j + 2m ≤ i} ⊆ ∆C( w[j + m .. i) ) : j ∈ J, k∗j ≤ i
Thus, we have
GetL(i) = GetA(i) ∪ GetNearTransitions(i, m)
On Time Complexity. Now we analyze the time complexity. From the discussion in Sections 11 and 12, each query of AuxiliaryEnumerator and the procedure GetNearTransitions(·) runs in constant time. Thus, InitializeL(·) and GetL(·) runs in constant time. To analyze the remaining queries, we define the potential Φ(Q) by (j,m′)∈Q(1 + log2 m′). Then, each call of AddL(·) increases Φ(Q) by at most 1 + log2 |w| ≤ O(log |w|), while each step of the loop in ShrinkL(·) defined by line 19 decreases Φ(Q) by at least 1. Therefore, AddL(·) and ShrinkL(·) runs in amortized O(log |w|)-time and O(1)-time, respectively.
11 Implementing AuxiliaryEnumerator
In this section, we implement AuxiliaryEnumerator, the data structure introduced in Section 10.2. It supports queries ShrinkA, AddA, and GetA in O(1) time. Some of the ideas in this section are common to RightEnumerator in Section 9, so we recommend reading that section first.
AuxiliaryEnumerator Depending Global Data Regex C, the entire string w, and factorization forest of C. Shared Data • a set of intervals J = {[j1, k1), [j2, k2), . . .} • a suffix w • a non-negative integer m Providing the following queries or methods: InitializeA(j) : Set w ← [j, n) and m ← n − j. AddA(j, k) : J ← J ∪ {[j, k)}. It is guaranteed that j + m ≤ k and w[j .. k) is a prefix of w. ShrinkA(d) : Set m ← m − d. It is guaranteed that d ≥ 0. GetA(i) : Return the set {TC( w[j + m .. i) ) : [j, k) ∈ J, k ≤ i}.
11.1 Overview
Differences from RightEnumerator. Although AuxiliaryEnumerator processes queries similar to RightEnumerator, the following points are different:
• The GetA(i) query in AuxiliaryEnumerator searches for indices j to the left of a given index i: i.e., [j, i), whereas GetR(i) query in RightEnumerator searches for indices j to the right of i: i.e., [i, j).
• AuxiliaryEnumerator maintains a set J of intervals [j, k), not a set J of indices j. Moreover, it is guaranteed that, for each [j, k) ∈ J,
– j + m ≤ k holds when it is added to J, and
– w[j .. k) is a prefix of pre-determined string w := w[j .. |w|].
• AuxiliaryEnumerator maintains an integer m, which decreases over time via ShrinkA(·) method and influences the output of GetA(·) method.
Defining Df and minidxf. As in the case of RightEnumerator, we utilize the factorization forest of C, where each node f corresponds to the interval [ℓf, rf). We define the Df and minidxf, which correspond to Df and maxidxf in RightEnumerator, respectively. Precisely, for each node f, we define
Df := {∆C( w[j + m .. rf) ) : [j, k) ∈ J, k ∈ [ℓf, rf)},
and for each idempotent node g and δ ∈ TC, we define
minidxg[δ] := min{t : 1 ≤ t ≤ q, δ ∈ Dft ⊙ eg},
where q is the number of children of g and ft is the t-th child of g. Note that the definitions of these values depend on m; in particular, they change as a result of ShrinkA queries.
For convenience, we also introduce the following notation:
Jf := { [j, k) ∈ J : k ∈ [ℓf, rf)}.
In words, Jf is the set of intervals of J whose right end is covered by f. Using this notation, we can rewrite Df as follows:
Df = {∆C( w[j + m .. rf) ) : [j, k) ∈ Jf}.
Lazy Update Strategy. If we manage Df and minidxg, then we can implement the GetA query in a way similar to the RightEnumerator (see Section 12 for a formal proof). However, it seems difficult to manage these values fully, because they depend on m, and every ShrinkA query requires updating all of them.
To resolve this issue, we adopt the so-called lazy update strategy; we postpone updating the values of Df and minidxg[·] until they are actually accessed. Precisely, we introduce two new methods UpdateA(f) and UpdateIdemA(g), which updates the values of Df and minidxg[·], respectively, to their correct values. Whenever the algorithm refers to these values (in both AddA and GetA queries), the corresponding UpdateA(f) or UpdateIdemA(g) is called once immediately beforehand.
For each node f, let mf be the value of m at the time when UpdateA(f) was last called (we explicitly manage this value mf together with the value described below). Since m only decreases, we always have m ≤ mf. Instead of maintaining Df, we manage the following:
DLf := {∆C( w[j + mf .. rf) ) : [j, k) ∈ Jf}.
The only difference from Df is the underlined part mf, which was m in Df.
Similarly, for each idempotent node g, let mIdemg be the value of m at the time when UpdateIdemA(g) was last called (similarly, we explicitly manage this value). Since m only decreases, we always have m ≤ mIdemg. Then, we manage the following:
minidxLg[δ] := min t : 1 ≤ t ≤ q, δ ∈ {∆C( w[j + mIdemg .. rft) ) : [j, k) ∈ Jft} ⊙ eg ,
where q is the number of children of g and ft is the t-th child of g. Note that the underlined part does not necessarily coincide with DLft because it evaluates w[j + mIdemg .. rft), not w[j + mft .. rft).
Since the definition of DLf and minidxLg[·] do not depend on m, these values do not change via ShrinkA queries. Moreover, if mf = m, DLf coincides Df, and if mIdemg = m, minidxLg[·] coincides minidxg[·].
Implementing UpdateA and UpdateIdemA. Now, we explain how to implement UpdateA and UpdateIdemA. We here use the invariant that, at any moment, for all nodes f and [j, k) ∈ Jf,
j + mf ≤ k, w[j .. j + mf) = w[j .. j + mf),
and for all idempotent node g and [j, k) ∈ Jg,
j + mIdemg ≤ k, w[j .. j + mIdemg) = w[j .. j + mIdemg).
These invariants are from the precondition of AddA(j, k), that is, j + m ≤ k and w[j .. k) is a prefix of w = w[j .. |w|]. Nevertheless, we defer the formal proofs of those invariants after we describe the precise implementation of AuxiliaryEnumerator.
The following lemma gives the update formula of DLf.
Lemma 66. Let f be a node and assume
j + mf ≤ k, w[j .. j + mf) = w[j .. j + mf)
holds for all [j, k) ∈ Jf. Then, we have
Df = ∆C( w[j + m .. j + mf) ) ⊙ DLf.
Proof. We have
Df = {∆C( w[j + m .. rf) ) : [j, k) ∈ Jf}
where the second equality follows from j + m ≤ j + mf ≤ k ≤ rf, and the third equality follows from w[j .. j + mf) = w[j .. j + mf).
The following lemma gives the update formula of minidxLg.
Lemma 67. Let g be an idempotent node and assume
j + mIdemg ≤ k, w[j .. j + mIdemg) = w[j .. j + mIdemg)
holds for all [j, k) ∈ Jg. Then, for each δ ∈ TC, we have
minidxg[δ] = min δ′∈TC minidxLg[δ′] : δ = ∆C( w[j + m .. j + mIdemg) ) ⊙ δ′ .
Proof. We denote the number of children of g by q and the t-th child of g by ft. Then, by the argument similar to the proof of Lemma 66, for each t, we have
Dft = ∆C( w[j + m .. j + mIdemg) ) ⊙ {∆C( w[j + mIdemg .. rft) ) : [j, k) ∈ Jft}.
Thus, we have
minidxg[δ] = min{t : 1 ≤ t ≤ q, δ ∈ Dft ⊙ eg}
Clearly, these updates can be computed in constant time.
11.2 Implementing AuxiliaryEnumerator
Now, we give an implementation of AuxiliaryEnumerator. Due to its length, we divide our implementation into three pseudocodes, Algorithms 6, 7, and 8.
Implementing InitializeA, ShrinkA, UpdateA, and UpdateIdemA. Algorithm 6 includes the methods InitializeA, ShrinkA, UpdateA, and UpdateIdemA. InitializeA(j) initializes j, m, DL, and minidxL, which seems to consume O(|w|) time. As done in RightEnumerator, we consider this runs in constant time by creating and initializing each node only when the data structure first accesses it.
ShrinkA(d) just reduces m by d and clearly runs in constant time. UpdateA(f) and UpdateIdemA(g) updates DLf and minidxLf, respectively, using Lemma 66 and Lemma 67, respectively, which also run in constant time.
Algorithm 6: Implementation of AuxiliaryEnumerator (first part). 1method InitializeA(j) Input: j ∈ [|w|] 2Initialize j; 3m ← |w| − j + 1; 4For each node f, mf ← m and DLf ← ∅; 5For each idempotent node g, mIdemg ← m and for each transition δ ∈ TC, minidxLg[δ] ← ∞; 6method ShrinkA(d) Input: 0 ≤ d ≤ m 7m ← m − d; 8method UpdateA(f) Input: A node f 9DLf ← ∆C( w[j + m .. j + mf) ) ⊙ DLf; 10mf ← m; 11method UpdateIdemA(g) Input: An idempotent node g 12foreach δ ∈ TC do 13minidxLg[δ] ← min δ′∈TC minidxLg[δ′] : δ = ∆C( w[j + m .. j + mIdemg) ) ⊙ δ′; 14mIdemg ← m;
Algorithm 7: Implementation of AuxiliaryEnumerator (second part). 1method AddA(j, k) Input: An interval [j, k) such that w[j .. k) is a prefix of w = w[j .. |w|] 2f ← the leaf node corresponding to the index k; 3while f is not root do 4g ← f.parent; 5UpdateA(f); 6δ ← ∆C( w[j + m .. rf) ); 7DLf.add(δ); 8if g is an idempotent node then 9UpdateIdemA(g); 10p ← g.childIdx(f) ; // f is the p-th child of g 11minidxLg[δ ⊙ eg] ← min(p, minidxLg[δ ⊙ eg]); 12f ← g;
Implementing AddA. Algorithm 7 implements the method AddA. As in previous algorithms, we adopt classes and modules; particularly, we write
• S.add(x) for the operation of adding the element x to the set S,
• f.parent to represent the parent of the node f,
• g.numOfChildren to represent the number of children of the node g,
• g.childOf(p) to represent the p-th child (from the left) of the node g (1-origin), and
• g.childIdx(f) to represent, for two nodes f and g with g = f.parent, an integer p such that f is the p-th child of g (from the left).
Now we prove the correctness of Algorithm 7. First, we prove the invariants used in Lemmas 66 and 67. It is clear that UpdateA and UpdateIdemA does not break those invariants because mf and mIdemg only decrease. Moreover, we remark that the method GetA, which we implement in Algorithm 8, does not change DL or minidxL other than by calling UpdateA or UpdateIdemA, and thus, does not break the invariant. Therefore, it suffices to prove the following two lemmas.
Lemma 68. Assume that
j + mf ≤ k, w[j .. j + mf) = w[j .. j + mf)
holds for all nodes f and [j, k) ∈ Jf. Then, after calling AddA(·), this invariant still holds.
Proof. Since mf does not increase, it suffices to prove that the invariant holds for the interval [j, k) that is newly added to J. Since the loop of line 3 iterates over all nodes f with k ∈ [ℓf, rf), UpdateA(f) is called for each f with [j, k) ∈ Jf, and particularly, mf is updated to m. Thus, from the precondition of AddA(j, k), the invariant holds.
Lemma 69. Assume that
j + mIdemg ≤ k, w[j .. j + mIdemg) = w[j .. j + mIdemg)
holds for all idempotent node g and [j, k) ∈ Jg. Then, after calling AddA(·), this invariant still holds.
Proof. Since mIdemf does not increase, it suffices to prove that the invariant holds for the interval [j, k) that is newly added to J. Since the loop of line 3 iterates over all idempotent nodes g with k ∈ [ℓg, rg), UpdateIdemA(g) is called for each g with [j, k) ∈ Jg, and particularly, mIdemg is updated to m. Thus, from the precondition of AddA(j, k), the invariant holds.
Combining Lemmas 66 and 68 yields that, after calling UpdateA(f), DLf coincides Df. Moreover, combining Lemmas 67 and 69 yields that, after calling UpdateIdemA(g), minidxLg coincides minidxg. These conditions continue to be satisfied until a ShrinkA query decreases m. Therefore, hereafter, we identify DLf with Df and minidxLg with minidxg on the nodes on which UpdateA and UpdateIdemA, respectively, are called after the last ShrinkA query.
The statements and proofs of Lemmas 70–73 are analogous to and almost same as those of Lemmas 57–60.
Lemma 70. Let j ∈ [|w|]. Then, the query AddA(j, k) adds ∆C( w[j + m .. rf) ) to Df for all nodes f with k ∈ [ℓf, rf) (and only for those nodes).
Proof. The loop defined in line 3 iterates over all nodes f with k ∈ [ℓf, rf). For each of such f, line 7 adds the transition ∆C( w[j + m .. rf) ) to Df.
Thus, we have the following, which is immediate from Lemma 70.
Lemma 71. Let J be a set of indices. Assume we have invoked AddA(j, k) once for each [j, k) ∈ J, in any order. Then, for every node f such that UpdateA(f) is called after the last ShrinkA query, Df = {∆C( w[j + m .. rf) ) : [j, k) ∈ Jf}.
We now ensure that the method AddA correctly updates minidxg[δ] by the following lemma.
Lemma 72. The query AddA(j, k) updates minidxg[δ] by min(p, minidxg[δ]) for all idempotent node g with k ∈ [ℓg, rg), where
• δ = ∆C( w[j + m .. rf) ) ⊙ eg, where f is the unique child of g with k ∈ [ℓf, rf), and
• p is the integer such that f is the p-th child of g,
and does not update other idempotent nodes.
Proof. The loop of line 3 iterates over all (g, f) satisfying the condition of the lemma, and line 11 is processed when and only when g is idempotent, f is the p-th child of g, and δ ⊙ eg = ∆C( w[j + m .. rf) ) ⊙ eg.
Now, we have the following.
Lemma 73. Let J be a set of intervals. Assume we have invoked AddA(j, k) once for each [j, k) ∈ J, in any order. Then, for each idempotent node g and δ ∈ TC, we have
maxidxg[δ] = max{t : 1 ≤ t ≤ q, δ ∈ Dft ⊙ eg}.
where q is the number of children of g and ft is the t-th child of g.
Proof. From Lemma 72, maxidxg[δ] is equal to the maximum among integers t such that there is an interval [j, k) ∈ J with
• k ∈ [ℓft, rft) ⊆ [ℓg, rg), where ft is the t-th child of g, and
• δ = ∆C( w[j + m, rft) ) ⊙ eg.
By definition of Dft, we have
{∆C( w[j + m .. rft) ) ⊙ eg : [j, k) ∈ Jft} = Dft ⊙ eg.
Thus, we have
maxidxg[δ] = max{t : 1 ≤ t ≤ q, ∃[j, k) ∈ Jft, δ = ∆C( w[j + m, rft) ) ⊙ eg}
Algorithm 8: Implementation of AuxiliaryEnumerator (third part). 1method GetA(i) Input: i ∈ [|w|] 2Let f be the leaf node corresponding to the index i; 3UpdateA(f); 4Accum ← DLf; 5while f is not root do 6g ← f.parent; 7p ← g.childIdx(f); // f is the p-th child of g 8if p > 1 then // IF: f is not the leftmost child of g 9f− ← g.childOf(p − 1) ; // f− is the immediate left sibling of f 10p ← g.childIdx(f−); 11UpdateA(f−); 12foreach δ ∈ DLf− do 13Accum.add δ ⊙ ∆C( w[rf− .. i) ); 14if g is an idempotent node then 15UpdateIdemA(g); 16foreach δ ∈ TC do 17if p − 1 > minidxLg[δ] then 18Accum.add δ ⊙ ∆C( w[rf− .. i) ); 19f ← g; 20return Accum;
Implementing GetA. Now, we give an implementation of the GetA method in Algorithm 8. Since the algorithm calls UpdateA(f−) immediately before using the value of DLf− and UpdateIdemA(g) immediately before using the value of minidxLg, as done in the analysis of AddA, we identify DLf− into Df and minidxLg into minidxg. The following lemma proves the correctness of the implementation, which is analogous to Lemma 61.
Lemma 74. Let i ∈ [|w|]. Then, GetA(i) returns the set {∆C( w[j + m .. i) ) : [j, k) ∈ J, k ≤ i}.
Proof. GetA(i) returns the union of
(i) Df for the leaf node f corresponding to the index i (line 4),
(ii) Df− ⊙ ∆C( w[rf− .. i) ) for each node f with i ∈ [ℓf, rf) that is not the leftmost child of the parent of f, where f− is the immediate left sibling of f (line 13), and
(iii) {δ ⊙ ∆C( w[rf− .. i) ) : δ ∈ TC, p − 1 > minidxg[δ]} for each node f with i ∈ [ℓf, rf) that is the non-leftmost p-th child of an idempotent node g, where f− is the immediate left sibling of f, (p − 1)-th child of g (line 18).
From now on, we rewrite these sets in a more manageable form.
(i). We have
Df = {∆C( w[j + m .. rf) ) : [j, k) ∈ Jf} = {∆C( w[j + m .. rf) ) : [j, k) ∈ J, k ∈ [ℓf, rf)}
where the first equality is from the definition of Df and the third equality is from the fact that f is the leaf.
(ii). For each node f satisfying the condition of (ii), we have
Df− ⊙ ∆C( w[rf− .. i) ) = {∆C( w[j + m .. rf−) ) ⊙ ∆C( w[rf− .. i) ) : [j, k) ∈ Jf−}
where the first equality is from the definition of Df−.
(iii). Let g be an idempotent node and f1, . . . , fp−1 = f−, fp = f, . . . , fq be its children such that i ∈ [ℓf, rf). Then, we obtain
{δ ⊙ ∆C( w[rf− .. i) ) : δ ∈ TC, minidxg[δ] < p − 1}
Now, it suffices to prove that the union of intervals
(I) consisting only of an index i,
(II) [ℓf−, rf−) for each pair of nodes (f, f−) defined in (ii), and
(III) [ℓg, ℓf−) for each tuple of nodes (g, f, f−) defined in (iii)
coincides with the interval [1, i]. We omit the proof, since it is identical to the corresponding part of the proof of Lemma 61, except that the left and right are interchanged.
On Time Complexity. Clearly, each query in Algorithms 6, 7, and 8 runs in time proportional to the depth of the factorization forest and |TC|, both of which are constants. Therefore, as desired, each query runs in constant time.
12 Enumerating Near Transitions
In this section, we construct GetNearTransitions(i, m), which we used in Section 10 but whose construction was deferred.
Recalling the setting. We first recall our setting. Let ST be the suffix tree of the string w, v be a vertex of ST, Hv and Lv be the set of indices in heavy and light subtree of v, respectively. We assume that the substring wB := Γ(v) corresponding to the root-v path is in L (B). We denote m := |wB|. Let i ∈ Lv be an index with w[i + m .. |w|] ∈ L (D).
The goal here is to give an O(log |w|)-time algorithm to compute the set
D := {∆C( w[j + m .. i) ) : j ∈ J, j + m ≤ i < j + 2m},
where
J = {j ∈ Hv : w[1 .. j) ∈ L (A)}.
Let
Hi,mv := {j ∈ Hv : j + m ≤ i < j + 2m}.
Then, we can rewrite D as:
D = {∆C( w[j + m .. i) ) : j ∈ Hi,mv, w[1 .. j) ∈ L (A)}.
Operations on Hv. We manage Hv by a balanced binary search tree (e.g., an AVL tree), which can perform the following O(log |Hv|)-time [24, Chap. 13]:
• Adding a value x to Hv.
• Checking if there is a value x in Hv.
• Given a value x, computing a successor/predecessor of x, i.e., min{y ∈ Hv : x < y} or max{y ∈ Hv : y < x}.
We can modify Algorithm 5 so that it additionally maintains this search tree as follows. In the InitializeL(·) method, we initialize the search tree. Each time the AddL(j) method is called, we add j into the search tree. This modification contributes to the time complexity of Left-B Transition Enumeration by only O(|ST[π]| log |w|), and thus does not affect the overall time complexity.
As in previous sections, we adopt classes or modules; particularly, we write Hv.succ(x) and Hv.pred(x) to represent the successor and predecessor of x in Hv, respectively.
Computing D. Now we consider computing D. Assuming Hi,mv is non-empty, we define the following two values:
j0 := min Hi,mv, jlast := max Hi,mv.
We note that j0 and jlast can be computed in O(log |w|)-time using Hv.succ(i − 2m) and Hv.pred(i − m + 1), as well as determining non-emptiness of Hi,mv.
If |Hi,mv| ≤ 2, we can compute D just by brute-forcing on Hi,mv. Note that whether |Hi,mv| ≤ 2 can be determined by the constant number of calls of successor operation. Now, we assume |Hi,mv| ≥ 3. Let ¯w := w[j0 .. jlast + m). The following lemma exploits the structure of Hi,mv and ¯w.
Lemma 75. ¯w is a periodic string: i.e., ¯w = θr for some prefix θ of ¯w and rational r > 1. Moreover, Hi,mv is an arithmetic progression with common difference d, where d is a period of ¯w.
Proof. Our proof is two-fold. First, we determine the common difference d. Next, we show the set {j0, j0 + d, j0 + 2d, . . . , jlast} coincides Hi,mv.
Determining d. Take arbitrary j ∈ Hi,mv \ {j0, jlast}. The positional relation among indices j0, j, and jlast are illustrated as follows.
Since j0, j ∈ Hi,mv ⊆ Hv, we have w[j0 .. j0 + m) = w[j .. j + m) = wB. Thus, wB[t] = wB[t + (j − j0)] holds for all t ∈ {1, . . . , m − (j − j0)}, and particularly, wB has a period (j − j0). Applying the same argument for j and jlast yields that wB has a period (jlast − j).
By the constraint i − 2m + 1 ≤ j0 < jlast ≤ i − m, the following holds:
|wB| = m > (i − m) − (i − 2m + 1) ≥ jlast − j0 = (jlast − j) + (j − j0).
Thus, we can apply Fine and Wilf’s Theorem (Lemma 10) to obtain that wB has a period
dj := gcd(j − j0, jlast − j) < m 2 ,
which is a divisor of jlast − j0. Let ej := (jlast − j0)/dj, which is an integer.
Let θj := wB[1 .. dj]. Then, wB = (θj)r for some rational r > 1. We also have w[j0 .. jlast) = θejj because it is a prefix of wB. Thus, we have
¯w = w[j0 .. jlast) w[jlast .. jlast + m) = θejj wB has period dj
also has a period dj. Since this holds for all j ∈ Hi,m \ {j0, jlast}, again from Fine and Wilf’s Theorem, ¯w has a period
d := gcd{dj : j ∈ Hi,mv \ {j0, jlast}},
where the reason why we can apply the Theorem is that, for any two j, j′ ∈ Hi,mv \ {j0, jlast}, dj + dj′ < m ≤ |¯w| holds.
Proving Hi,mv forming an arithmetic progression. Let e = (jlast − j0)/d. To complete the proof, we prove
Hi,mv = {j0 + kd : k ∈ {0, 1, . . . , e}}.
(⊆): Let j ∈ Hi,mv. If j = j0, we have j = j0 + 0 · d. Moreover, if j = jlast, we have j = j0 + ed. Otherwise, take dj defined above, which divides d and is a divisor of j − j0. It leads that there is an integer kj with j = j0 + kjd, which satisfies 0 < kj < e because of j0 < j < jlast.
(⊇): Conversely, let k ∈ {0, 1, . . . , e}. If k = 0, we have j0 + kd = j0 ∈ Hi,mv. Moreover, if k = e, we have j0 + kd = jlast ∈ Hi,mv. Assume otherwise. Since ¯w = w[j0 .. jlast + m) has a period d, we have w[j0 + kd .. j0 + kd + m) = w[j0 .. j0 + m) = wB. Thus, j0 + kd is either in Hv or Lv. Moreover, again from periodicity, we have w[j0 + kd + m] = w[j0 + m]; that is, the letter immediately after the substring w[j0 + kd .. j0 + kd + m) is same as that of the substring w[j0 .. j0 + m). Thus, combining with the fact that j0 ∈ Hv, we have j0 + kd ∈ Hv, and thus, j0 + kd ∈ Hi,mv.
From Lemma 75, we can write Hi,mv = {j0 + kd : k ∈ {0, 1, . . . , e}} using a tuple (j0, d, e). This tuple (j0, d, e) can be computed in O(log |w|)-time as follows. First, we compute the smallest element j0, the second smallest element j1, and the largest element jlast of Hi,mv in O(log |w|)-time using the successor/predecessor queries on Hv. Then, we have d = j1 − j0 and e = (jlast − j0)/(j1 − j0).
On (j0, d, e), we define two substrings θ1 := w[j0 .. j0 + d), and θ2 := w[j0 + m .. j0 + m + d). Since ¯w has a period d that divides jlast − j0, we have
¯w = θe1 wB = wB θe2.
Let w1 := w[1 .. j0) and w2 := w[jlast + m .. i). We define
SA := {k ≥ 0 : w1 θk1 ∈ L (A)},
and for each δ ∈ TC,
SC,δ := {k ≥ 0 : ∆C(θk2 w2) = δ}.
From Lemma 46, SA and SC,δ are ultimately periodic. Moreover, for every transition δ of C, the following set
Sδ := SA + Minkowski Sum SC,δ
is also ultimately periodic because of Lemma 14. Furthermore, if we write Sδ = (µ, M, λ, T), µ and λ are bounded by a constant that depends only on A and C. Now, we have the following.
Lemma 76. A transition δ ∈ TC is in D if and only if e ∈ Sδ.
Proof. (⇒): Assume δ ∈ D. Then, there is an index j ∈ Hi,mv such that w[1 .. j) ∈ L (A) and ∆C( w[j + m .. i) ) = δ. From Lemma 75, j = j0 + kd holds for some k ∈ {0, . . . , e}, and thus,
w[1 .. j) = w1 w[j0 .. j) = w1 θk1,
which implies k ∈ SA. Moreover, we have
w[j + m .. i) = w[j + m .. jlast + m) w2 = θe−k2 w2,
and thus, e − k ∈ SC,δ. Therefore, from the definition of the Minkowski sum, we have e = k + (e − k) ∈ SA + SC,δ = Sδ.
(⇐): Let e ∈ Sδ. Then, there is an integer k ∈ {0, . . . , e} with k ∈ SA and e − k ∈ SC,δ. Let j = j0 + kd. Then, we have
w[1 .. j) = w1 w[j0 .. j) = w1 w[j0 .. j0 + kd) = w1 θk ∈ L (A) .
Moreover, we have
∆C( w[j + m .. i) ) = ∆C(w[j + m .. jlast + m) w2) = ∆C(θe−k2 w2) = δ,
where the last equality is from e − k ∈ SC,δ. Therefore, we have δ ∈ D and the lemma is proved.
On Time Complexity. Since Sδ depends only on A and C, we can compute it in constant time, as well as determining if e ∈ Sδ. Computing e takes O(log |w|) time. Thus, from Lemma 76, the desired set D can be computed in O(log |w|) time.
References
[1] A. Abboud and V. V. Williams. Popular conjectures imply strong lower bounds for dynamic problems. In FOCS ’14, pages 434–443. IEEE Computer Society, 2014. doi:10.1109/FOCS.2014.53.
[2] A. Abboud and V. V. Williams. Popular conjectures imply strong lower bounds for dynamic problems, 2014. arXiv:1402.0054, doi:10.48550/arXiv.1402.0054.
[3] A. V. Aho. Algorithms for finding patterns in strings. In J. van Leeuwen, editor, Handbook of Theoretical Computer Science, Volume A: Algorithms and Complexity, pages 255–300. MIT Press, 1990. doi:10.1016/B978-0-444-88071-0.50010-2.
[4] A. V. Aho, R. Sethi, and J. D. Ullman. Compilers: Principles, Techniques, and Tools. Addison-Wesley, 1986. URL: https://www.worldcat.org/oclc/12285707.
[5] A. Amir, T. Kopelowitz, A. Levy, S. Pettie, E. Porat, and B. R. Shalom. Mind the gap! online dictionary matching with one gap. Algorithmica, 81:2123–2157, 2019. doi:10.1007/s00453-018-0526-2.
[6] D. Angluin. Finding patterns common to a set of strings (extended abstract). In STOC ’79, pages 130–141. ACM, 1979. doi:10.1145/800135.804406.
[7] D. Angluin. Finding patterns common to a set of strings. JCSS, 21(1):46–62, 1980. doi:10.1016/0022-0000(80)90041-0.
[8] Anonymous Author(s). Checking quadratic behaviors of regex of cloudflare outage. https://regex101.com/r/hidvB3/1/debugger, 2025.
[9] Anonymous Author(s). Checking quadratic behaviors of regex of stack overflow outage. https://regex101.com/r/pR6DbC/1/debugger, 2025.
[10] A. Backurs and P. Indyk. Which Regular Expression Patterns Are Hard to Match? . In FOCS, pages 457–466. IEEE Computer Society, 2016. doi:10.1109/FOCS.2016.56.
[11] A. Barrière and C. Pit-Claudel. Linear matching of javascript regular expressions. Proc. ACM Program. Lang., 8(PLDI), jun 2024. doi:10.1145/3656431.
[12] M. Berglund and B. van der Merwe. Re-examining regular expressions with backreferences. Theor. Comput. Sci., 940(Part):66–80, 2023. doi:10.1016/j.tcs.2022.10.041.
[13] P. Bille and I. L. Gørtz. Sparse regular expression matching. In SODA 2024, pages 3354–3375. SIAM, 2024. doi:10.1137/1.9781611977912.120.
[14] P. Bille, I. L. Gørtz, H. W. Vildhøj, and D. K. Wind. String matching with variable length gaps. Theoretical Computer Science, 443:25–34, 2012. doi:10.1016/j.tcs.2012.03.029.
[15] M. Bojańczyk. Algorithms for regular languages that use algebra. SIGMOD Rec., 41(2):5–14, aug 2012. doi:10.1145/2350036.2350038.
[16] M. Bojańczyk. Languages recognised by finite semigroups, and their generalisations to objects such as trees and graphs, with an emphasis on definability in monadic second-order logic. CoRR, abs/2008.11635, 2020. arXiv:2008.11635, doi:10.48550/arxiv.2008.11635.
[17] M. Bojańczyk and P. Parys. Efficient evaluation of nondeterministic automata using factorization forests. In S. Abramsky, C. Gavoille, C. Kirchner, F. Meyer auf der Heide, and P. G. Spirakis, editors, ICALP, pages 515–526. Springer, 2010. doi:10.1007/978-3-642-14165-2\_44.
[18] K. Bringmann, A. Grønlund, M. Künnemann, and K. G. Larsen. The NFA Acceptance Hypothesis: Non-Combinatorial and Dynamic Lower Bounds. In ITCS 2024, volume 287 of LIPIcs, pages 22:1–22:25. Schloss Dagstuhl, 2024. doi:10.4230/LIPIcs.ITCS.2024.22.
[19] A. Buckles. simple-markdown: inlinecode: Fix ReDoS & improve escape semantics (commit 89797fe). GitHub commit, 2019. URL: https://github.com/ariabuckles/simple-markdown/commit/89797fe.
[20] A. K. Chandra, D. C. Kozen, and L. J. Stockmeyer. Alternation. J. ACM, 28(1):114–133, jan 1981. doi:10.1145/322234.322243.
[21] A. Chattopadhyay, A. W. Li, and K. Mamouras. Verified and efficient matching of regular expressions with lookaround. In Proceedings of the 14th ACM SIGPLAN International Conference on Certified Programs and Proofs, CPP ’25, pages 198–213. ACM, 2025. doi:10.1145/3703595.3705884.
[22] C. Choffrut and J. Karhumäki. Combinatorics of words. In G. Rozenberg and A. Salomaa, editors, Handbook of Formal Languages, Volume 1: Word, Language, Grammar, pages 329–438. Springer, 1997. doi:10.1007/978-3-642-59136-5_6.
[23] T. Colcombet. The factorisation forest theorem. In J. Pin, editor, Handbook of Automata Theory, pages 653–693. European Mathematical Society Publishing House, Zürich, Switzerland, 2021. doi:10.4171/Automata-1/18.
[24] T. H. Cormen, C. E. Leiserson, R. L. Rivest, and C. Stein. Introduction to Algorithms, fourth edition. MIT Press, 2022. URL: https://mitpress.mit.edu/9780262046305/introduction-to-algorithms/.
[25] R. Cox. Regular expression matching can be simple and fast. https://swtch.com/~rsc/regexp/regexp1.html, January 2007.
[26] R. Cox. Regular expression matching in the wild. https://swtch.com/~rsc/regexp/regexp3.html, mar 2010.
[27] M. Crochemore. An optimal algorithm for computing the repetitions in a word. Information Processing Letters, 12(5):244–250, 1981. doi:10.1016/0020-0190(81)90024-7.
[28] M. Crochemore, C. Hancart, and T. Lecroq. Algorithms on Strings. Cambridge University Press, 2007. doi:10.1017/CBO9780511546853.
[29] M. Crochemore and W. Rytter. Jewels of stringology. World Scientific, 2002. doi:10.1142/4838.
[30] S. A. Crosby. Denial of service through regular expressions. USENIX Association, 2003. URL: https://www.usenix.org/conference/12th-usenix-security-symposium/denial-service-through-regular-expressions.
[31] S. A. Crosby and D. S. Wallach. Denial of service via algorithmic complexity attacks. In 12th USENIX Security Symposium (USENIX Security 03). USENIX Association, 2003. URL: https://www.usenix.org/conference/12th-usenix-security-symposium/denial-service-algorithmic-complexity-attacks.
[32] M. Cygan, F. V. Fomin, L. Kowalik, D. Lokshtanov, D. Marx, M. Pilipczuk, M. Pilipczuk, and S. Saurabh. Parameterized Algorithms. Springer, 2015. doi:10.1007/978-3-319-21275-3.
[33] R. Dąbrowski and W. Plandowski. Solving two-variable word equations (extended abstract). In J. Díaz, J. Karhumäki, A. Lepistö, and D. Sannella, editors, Automata, Languages and Programming: 31st International Colloquium, ICALP 2004, Turku, Finland, July 12-16, 2004. Proceedings, volume 3142 of Lecture Notes in Computer Science, pages 408–419. Springer, 2004. doi:10.1007/978-3-540-27836-8_36.
[34] R. Dąbrowski and W. Plandowski. On word equations in one variable. Algorithmica, 60(4):819–828, Aug 2011. doi:10.1007/s00453-009-9375-3.
[35] J. C. Davis, F. Servant, and D. Lee. Using selective memoization to defeat regular expression denial of service (redos). In SP’21, pages 1–17, 2021. doi:10.1109/SP40001.2021.00032.
[36] V. Diekert, C. Gutierrez, and C. Hagenah. The existential theory of equations with rational constraints in free groups is pspace-complete. Inf. Comput., 202(2):105–140, 2005. doi:10.1016/j.ic.2005.04.002.
[37] R. G. Downey and M. R. Fellows. Fixed-parameter tractability and completeness i: Basic results. SIAM Journal on Computing, 24(4):873–921, 1995. doi:10.1137/S0097539792228228.
[38] L. Duraj, M. Künnemann, and A. Polak. Tight conditional lower bounds for longest common increasing subsequence. Algorithmica, 81(10):3968–3992, 2019. doi:10.1007/S00453-018-0485-7.
[39] A. Ehrenfeucht and G. Rozenberg. Finding a homomorphism between two words in np-complete. Information Processing Letters, 9(2):86–88, 1979. doi:10.1016/0020-0190(79)90135-2.
[40] H. Fernau, F. Manea, R. Mercaş, and M. L. Schmid. Pattern Matching with Variables: Fast Algorithms and New Hardness Results. In STACS 2015, volume 30 of LIPIcs, pages 302–315. Schloss Dagstuhl, 2015. doi:10.4230/LIPIcs.STACS.2015.302.
[41] H. Fernau, F. Manea, R. Mercaş, and M. L. Schmid. Pattern matching with variables: Efficient algorithms and complexity results. ACM Trans. Comput. Theory, 12(1), feb 2020. doi:10.1145/3369935.
[42] H. Fernau and M. L. Schmid. Pattern matching with variables: A multivariate complexity analysis. Inf. Comput., 242:287–305, 2015. doi:10.1016/j.ic.2015.03.006.
[43] H. Fernau, M. L. Schmid, and Y. Villanger. On the parameterised complexity of string morphism problems. Theory of Computing Systems, 59(1):24–51, 2016. doi:10.1007/s00224-015-9635-3.
[44] N. J. Fine and H. S. Wilf. Uniqueness theorems for periodic functions. Proceedings of the American Mathematical Society, 16(1):109–114, 1965. doi:10.2307/2034009.
[45] M. J. Fischer and A. R. Meyer. Boolean matrix multiplication and transitive closure. In Annual Symposium on Switching and Automata Theory, pages 129–131, 1971. doi:10.1109/SWAT.1971.4.
[46] K. Fredriksson and S. Grabowski. Efficient algorithms for pattern matching with general gaps, character classes, and transposition invariance. Information Retrieval, 11:335–357, 2008. doi:10.1007/s10791-008-9054-z.
[47] D. D. Freydenberger and M. L. Schmid. Deterministic regular expressions with back-references. J. Comput. Syst. Sci., 105:1–39, 2019. doi:10.1016/j.jcss.2019.04.001.
[48] J. Friedl. Mastering Regular Expressions. O’Reilly, 2006. URL: https://www.oreilly.com/library/view/mastering-regular-expressions/0596528124/.
[49] H. Fujinami and I. Hasuo. Efficient matching with memoization for regexes with look-around and atomic grouping. In S. Weirich, editor, 33rd European Symposium on Programming, ESOP 2024, volume 14577 of Lecture Notes in Computer Science, pages 90–118. Springer, 2024. doi:10.1007/978-3-031-57267-8\_4.
[50] M. Furman. Application of a method of rapid multiplication of matrices to the problem of finding the transitive closure of a graph. Doklady Akademii Nauk, 194(3):524–524, 1970. URL: https://www.mathnet.ru/eng/dan35686.
[51] A. Gajentaan and M. H. Overmars. On a class of O(n2) problems in computational geometry. Computational Geometry, 5(3):165–185, 1995. doi:10.1016/0925-7721(95)00022-2.
[52] S. Ginsburg and E. H. Spanier. Semigroups, Presburger formulas, and languages. Pacific Journal of Mathematics, 16(2):285–296, 1966. doi:10.2140/pjm.1966.16.285.
[53] J. Goyvaerts. Runaway Regular Expressions: Catastrophic Backtracking. https://www.regular-expressions.info/catastrophic.html, 2021.
[54] J. Goyvaerts. Atomic grouping. https://www.regular-expressions.info/atomic.html, 2025.
[55] J. Goyvaerts. Lookahead and Lookbehind Zero-Length Assertions. https://www.regular-expressions.info/lookaround.html, 2025.
[56] J. Goyvaerts. Repetition with star and plus. https://www.regular-expressions.info/repeat.html, 2025.
[57] J. Graham-Cumming. Details of the Cloudflare outage on July 2, 2019. Cloudflare Blog. Archived at https://web.archive.org/web/20190712160002/https://blog.cloudflare.com/details-of-the-cloudflare-outage-on-july-2-2019/, July 2019. URL: https://blog.cloudflare.com/details-of-the-cloudflare-outage-on-july-2-2019/.
[58] D. Gusfield. Algorithms on Strings, Trees, and Sequences - Computer Science and Computational Biology. Cambridge University Press, 1997. doi:10.1017/cbo9780511574931.
[59] T. Haapasalo, P. Silvasti, S. Sippu, and E. Soisalon-Soininen. Online dictionary matching with variable-length gaps. In Experimental Algorithms, volume 6630 of Lecture Notes in Computer Science, pages 76–87. Springer, 2011. doi:10.1007/978-3-642-20662-7_7.
[60] J. C. Hansen, A. H. Kjelstrøm, and A. Pavlogiannis. Tight bounds for reachability problems on one-counter and pushdown systems. Inf. Process. Lett., 171:106135, 2021. doi:10.1016/j.ipl.2021.106135.
[61] M. Holzer. Comments on monoids induced by NFAs. IFIG Research Report 2301, Institut für Informatik, Universität Giessen, March 2023. URL: https://jlupub.ub.uni-giessen.de/items/c469513c-e738-48ae-900b-397efc96b042, doi:10.22029/jlupub-14955.
[62] W.-K. Hon, T.-W. Lam, R. Shah, S. V. Thankachan, H.-F. Ting, and Y. Yang. Dictionary matching with a bounded gap in pattern or in text. Algorithmica, 80:698–713, 2018. doi:10.1007/s00453-017-0288-2.
[63] O. H. Ibarra, T. Pong, and S. M. Sohn. A note on parsing pattern languages. Pattern Recognit. Lett., 16(2):179–182, 1995. doi:10.1016/0167-8655(94)00091-G.
[64] A. Jeż. One-variable word equations in linear time. Algorithmica, 74(1):1–48, 2016. doi:10.1007/s00453-014-9931-3.
[65] A. Jeż. Recompression: A simple and powerful technique for word equations. J. ACM, 63(1), feb 2016. doi:10.1145/2743014.
[66] A. Jeż. Solving Word Equations (And Other Unification Problems) by Recompression. In M. Fernández and A. Muscholl, editors, 28th EACSL Annual Conference on Computer Science Logic, CSL 2020, Barcelona, Spain, January 13-16, 2020, volume 152 of LIPIcs, pages 3:1–3:17. Schloss Dagstuhl - Leibniz-Zentrum für Informatik, 2020. doi:10.4230/LIPIcs.CSL.2020.3.
[67] T. Jiang, E. Kinber, A. Salomaa, K. Salomaa, and S. Yu. Pattern languages with and without erasing. International Journal of Computer Mathematics, 50(3–4):147–163, 1994. doi:10.1080/00207169408804252.
[68] T. Kopelowitz, S. Pettie, and E. Porat. Higher lower bounds from the 3SUM conjecture. In SODA 2016, pages 1272–1287. SIAM, 2016. doi:10.1137/1.9781611974331.ch89.
[69] M. Kufleitner. A proof of the factorization forest theorem, 2007. URL: https://arxiv.org/abs/0710.5130, arXiv:0710.5130, doi:10.48550/arXiv.0710.5130.
[70] M. Kufleitner. The height of factorization forests. In E. Ochmański and J. Tyszkiewicz, editors, MFCS, pages 443–454. Springer, 2008. doi:10.1007/978-3-540-85238-4\_36.
[71] R. E. Ladner, R. J. Lipton, and L. J. Stockmeyer. Alternating pushdown and stack automata. SIAM Journal on Computing, 13(1):135–155, 1984. doi:10.1137/0213010.
[72] A. Levy and B. R. Shalom. A comparative study of dictionary matching with gaps: Limitations, techniques and challenges. Algorithmica, 84:590–638, 2022. doi:10.1007/s00453-021-00851-6.
[73] K. Mamouras and A. Chattopadhyay. Efficient matching of regular expressions with lookaround assertions. Proc. ACM Program. Lang., 8(POPL), jan 2024. doi:10.1145/3632934.
[74] A. Mateescu and A. Salomaa. Aspects of classical language theory. In G. Rozenberg and A. Salomaa, editors, Handbook of Formal Languages, Volume 1: Word, Language, Grammar, pages 175–251. Springer, 1997. doi:10.1007/978-3-642-59136-5_4.
[75] MITRE. CWE-1333: Inefficient Regular Expression Complexity. https://cwe.mitre.org/data/definitions/1333.html, 2021. CWE version 4.17. Page last updated: 2025-04-03.
[76] J. I. Munro. Efficient determination of the transitive closure of a directed graph. Inf. Process. Lett., 1(2):56–58, 1971. doi:10.1016/0020-0190(71)90006-8.
[77] National Vulnerability Database (NVD). CVE-2017-16114. https://nvd.nist.gov/vuln/detail/cve-2023-6159, 2017. GitLab Security Release:. URL: https://nvd.nist.gov/vuln/detail/CVE-2017-16114.
[78] National Vulnerability Database (NVD). CVE-2019-25103. https://nvd.nist.gov/vuln/detail/cve-2023-6159, 2019. GitLab Security Release:. URL: https://nvd.nist.gov/vuln/detail/CVE-2019-25103.
[79] National Vulnerability Database (NVD). CVE-2021-21240. https://nvd.nist.gov/vuln/detail/CVE-2021-21240, 2021. GitHub Advisory:. URL: https://github.com/advisories/GHSA-93xj-8mrv-444m.
[80] National Vulnerability Database (NVD). CVE-2023-39663. https://nvd.nist.gov/vuln/detail/CVE-2023-39663, 2023. GitHub Advisory:. URL: https://github.com/advisories/GHSA-v638-q856-grg8.
[81] National Vulnerability Database (NVD). CVE-2023-6159. https://nvd.nist.gov/vuln/detail/cve-2023-6159, 2023. GitLab Security Release:. URL: https://about.gitlab.com/releases/2024/01/25/critical-security-release-gitlab-16-8-1-released/.
[82] National Vulnerability Database (NVD). CVE-2024-26142. https://nvd.nist.gov/vuln/detail/CVE-2024-26142, 2024. GitHub Advisory:. URL: https://github.com/advisories/GHSA-jjhx-jhvp-74wq.
[83] National Vulnerability Database (NVD). CVE-2024-28865. https://nvd.nist.gov/vuln/detail/CVE-2024-28865, 2024. GitHub Advisory:. URL: https://github.com/advisories/GHSA-wj85-w4f4-xh8h.
[84] National Vulnerability Database (NVD). CVE-2025-25200. https://nvd.nist.gov/vuln/detail/CVE-2025-25200, 2025. GitHub Advisory:. URL: https://github.com/advisories/GHSA-593f-38f6-jp5m.
[85] National Vulnerability Database (NVD). CVE-2025-29907. https://nvd.nist.gov/vuln/detail/CVE-2025-29907, 2025. GitHub Advisory:. URL: https://github.com/advisories/GHSA-w532-jxjh-hjhj.
[86] National Vulnerability Database (NVD). CVE-2025-5197. https://nvd.nist.gov/vuln/detail/CVE-2025-5197, 2025. GitHub Advisory:. URL: https://github.com/advisories/GHSA-9356-575x-2w9m.
[87] G. Navarro and M. Raffinot. Fast and simple character classes and bounded gaps pattern matching, with applications to protein searching. Journal of Computational Biology, 10(6):903–923, 2003. doi:10.1089/106652703322756140.
[88] T. Nogami and T. Terauchi. Efficient matching of some fundamental regular expressions with backreferences. In MFCS 2025, volume 345 of LIPIcs, pages 81:1–81:19. Schloss Dagstuhl, 2025. doi:10.4230/LIPIcs.MFCS.2025.81.
[89] T. Nogami and T. Terauchi. Hardness of regular expression matching with extensions, 2026. URL: https://arxiv.org/abs/2601.03020, arXiv:2601.03020, doi:10.48550/arXiv.2601.03020.
[90] M. Pătraşcu. Towards polynomial lower bounds for dynamic problems. In STOC 2010, pages 603–610. ACM, 2010. doi:10.1145/1806689.1806772.
[91] M. Pătraşcu and R. Williams. On the possibility of faster sat algorithms. In SODA ’10, pages 1065–1075. SIAM, 2010. doi:10.1137/1.9781611973075.86.
[92] J.-É. Pin. Finite semigroups and recognizable languages: an introduction. NATO Advanced Study Institute, pages 1–32, 1995. URL: https://www.irif.fr/~jep/Resumes/York1.html.
[93] J.-É. Pin. Syntactic semigroups. In G. Rozenberg and A. Salomaa, editors, Handbook of Formal Languages, Volume 1: Word, Language, Grammar, pages 679–746. Springer, 1997. doi:10.1007/978-3-642-59136-5\_10.
[94] W. Plandowski. Satisfiability of word equations with constants is in pspace. J. ACM, 51(3):483–496, may 2004. doi:10.1145/990308.990312.
[95] J. Sakarovitch. Elements of Automata Theory. Cambridge University Press, 2009. doi:10.1017/CBO9781139195218.
[96] M. L. Schmid. Regular expressions with backreferences: Polynomial-time matching techniques. J. Autom. Lang. Comb., 29(2-4):321–357, 2024. doi:10.25596/jalc-2024-321.
[97] K. U. Schulz. Makanin’s algorithm for word equations - two improvements and a generalization. In Word Equations and Related Topics, First International Workshop, IWWERT ’90, Tübingen, Germany, October 1-3, 1990, Proceedings, volume 572 of Lecture Notes in Computer Science, pages 85–150. Springer, 1990. doi:10.1007/3-540-55124-7\_4.
[98] R. Sedgewick and K. Wayne. Algorithms, 4th Edition. Addison-Wesley, 2011. URL: https://algs4.cs.princeton.edu/home/.
[99] T. Shinohara. Polynomial time inference of extended regular pattern languages. In RIMS Symposia on Software Science and Engineering, pages 115–127. Springer, 1983. doi:10.1007/3-540-11980-9_19.
[100] I. Simon. Factorization forests of finite height. Theoretical Computer Science, 72(1):65–94, 1990. doi:10.1016/0304-3975(90)90047-L.
[101] Stack Exchange. Outage Postmortem - July 20, 2016. Stack Exchange Network Status Blog. Archived at https://web.archive.org/web/20180801005940/http://stackstatus.net/post/147710624694/outage-postmortem-july-20-2016, July 2016. URL: http://stackstatus.net/post/147710624694/outage-postmortem-july-20-2016.
[102] F. Stephan, R. Yoshinaka, and T. Zeugmann. On the parameterised complexity of learning patterns. In Computer and Information Sciences II, pages 277–281. Springer, 2012. doi:10.1007/978-1-4471-2155-8_35.
[103] K. Thompson. Programming techniques: Regular expression search algorithm. Commun. ACM, 11(6):419–422, jun 1968. doi:10.1145/363347.363387.
[104] Y. Uezato. Regular Expressions with Backreferences and Lookaheads Capture NLOG. In ICALP 2024, volume 297 of LIPIcs, pages 155:1–155:20. Schloss Dagstuhl, 2024. doi:10.4230/LIPIcs.ICALP.2024.155.
[105] UziTech. marked: fix inline code regex (commit 3271b8b). GitHub commit, 2018. URL: https://github.com/markedjs/marked/commit/3271b8b.
[106] R. Williams. A new algorithm for optimal 2-constraint satisfaction and its implications. Theor. Comput. Sci., 348(2-3):357–365, 2005. doi:10.1016/j.tcs.2005.09.023.
[107] V. V. Williams. On some fine-grained questions in algorithms and complexity. In Proceedings of the International Congress of Mathematicians (ICM 2018). WORLD SCIENTIFIC, 2019. doi:10.1142/9789813272880_0188.
A Proof of Lemma for Closure Properties of Ultimately Periodic Sets
We prove Lemma 14 in Section 2.
Lemma 14. Let P and Q be two ultimately periodic sets. Then, we have the following.
• The union P ∪ Q is ultimately periodic.
• The Minkowski sum P + Q := {p + q : p ∈ P, q ∈ Q} is ultimately periodic.
• For any positive integer e, the set e · P := {ep : p ∈ P} is ultimately periodic.
Proof. Let P = (µ, M, λ, T) and Q = (µ′, M′, λ′, T′). Moreover, let ¯λ be the least common multiple of λ and λ′.
Union: It suffices to prove that for i ≥ max(µ, µ′), i ∈ P ∪ Q if and only if i + ¯λ ∈ P ∪ Q. Assume i ∈ P ∪ Q. Then, we have either i ∈ P and i ∈ Q. In the case where i ∈ P, we have i ≥ max(µ, µ′) ≥ µ, and thus, (i mod λ) ∈ T. Thus, we have ((i + ¯λ) mod λ) ∈ T, which implies i + ¯λ ∈ P ⊆ P ∪ Q because i + ¯λ ≥ µ. The same argument also works for the case of i ∈ Q. Thus, we have i + ¯λ ∈ P ∪ Q. The inverse direction is proved in the same way.
Minkowski Sum: It suffices to prove that for i ≥ µ + µ′ + ¯λ, i ∈ P ∪ Q holds if and only if i + ¯λ ∈ P + Q. Assume i ∈ P + Q. Then, there is a pair of integers j ∈ P and k ∈ Q with j + k = i. Since j + k = i ≥ µ + µ′, we have either (j mod λ) ∈ T or (k mod λ′) ∈ T′. If (j mod λ) ∈ T, we have ((j + ¯λ) mod λ) ∈ T and thus, j + ¯λ ∈ P. Thus, i + ¯λ = (j + ¯λ) + k ∈ P + Q. The same argument also holds for the case (k mod λ′) ∈ T′. Therefore, we have i + ¯λ ∈ P + Q.
For the inverse direction, assume i + ¯λ ∈ P + Q. Then, there is a pair of integers j′ ∈ P and k′ ∈ Q with j′ + k′ = i + ¯λ. Since j′ + k′ − 2¯λ = i − ¯λ ≥ µ + µ′, we have either j′ − ¯λ ≥ µ or k′ − ¯λ ≥ µ′. If the former holds, since ((j′ − ¯λ) mod λ) ∈ T, we have i = (j′ − ¯λ) + k′ ∈ P + Q. The same argument also holds for the latter case. Therefore, we have i ∈ P + Q.
e-Multiplication: The set e · P is equal to (eµ, e · M, eλ, e · T).
B Normalizing 1-use REWB: Proof of Theorem 6
In this section, we prove our Theorem 6 for 1-use REWB.
Theorem 6. For any 1-use REWB E, there exists an equivalent REWB of the following form:
(A1 (B1)x C1 \x D1) + (A2 (B2)x C2 \x D2) + · · · + (AK (BK)x CK\x DK) + E′
where Ai, Bi, Ci, Di, E′ are Regexes. We can construct the above representation in O(|E|4) time. Furthermore, the following holds for their size:
K = O(|E|2), |Ai| = O(|E|2), |Bi| = O(|E|), |Ci| = O(|E|2), |Di| = O(|E|), |E′| = O(|E|2).
Structure of This Appendix. We prove Theorem 6 by combining Lemmas 77 and 78. After introducing the required definitions through Sections B.1 and B.2, we prove Lemma 77 in Section B.3.
Lemma 77 (Normalizing First Step). Let E be a 1-use REWB. Then, we can decompose E into the following form:
(α1 \x D1) + (α2 \x D2) + · · · + (αK′ \x DK′) + Φ
where each αi is a reference-free (i.e., not including \y for any y) and Di and Φ are Regex rather than REWB. In particular, the following holds:
K′ ≤ |E|, |αi| = O(|E|), |Dj| = O(|E|), |Φ| = O(|E|).
After proving this lemma, in Section B.4, we transform αi into a corresponding expression generated by the following restricted grammar:
H ::= ϵ | σ | H H | H + H | H∗ | [REGEX]x.
Then we prove the second phase lemma in Section B.5.
Lemma 78 (Normalizing Second Step). Let α be an expression of the restricted grammar H. Then, we can decompose α into the following form:
(A1 [B1]x C1) + (A2 [B2]x C2) + · · · + (AK′′ [BK′′]x CK′′) + Ψ,
where Ai, Bi, Ci, and Ψ are Regexes.
In particular, the following holds for each expression size:
K′′ ≤ |E|, |Ai| = O(|E|2), |Bi| ≤ |E|, |Ci| = O(|E|2), |Ψ| ≤ |E|.
Combining Lemmas 77 and 78 immediately leads to our Theorem 6.
B.1 Basic Definitions
We first recall and introduce required definitions.
REWB. Let Σ be a finite alphabet and V be a finite set of variables. The set of regular expressions with backreferences (REWB) extends standard regular expressions (Regex) and is defined by the following grammar:
E ::= ϵ | σ | ∅ | E · E | E + E | (E)∗ | [E]x | \x
where σ ∈ Σ and x ∈ V.
Notation Remark: In this appendix, for ease of readability
• We sometimes write [ E ]x instead of ( E )x to distinguish them from parentheses.
• We sometimes simply write E1E2 instead of E1 · E2 by omitting the symbol ·.
Term: Binding and Reference. We call each term of the form [· · · ]x a binding and one of the form \x a reference.
Size of Expression: |E|. Here we define the size of expressions E as the total number of nodes of the abstract syntax tree of E. Formally, |E| is defined by the size function size(E) as follows:
size(t) := 1, (for t ∈ {ϵ, σ, ∅, \x}), size(E1 ⋄ E2) := size(E1) + size(E2) + 1, (for ⋄ ∈ { · , + }) size( (E)∗ ) := size(E) + 1, size( [E]x ) := size(E) + 1.
REGEX. We define the fragment Regex by the following grammar:
ER ::= ϵ | σ | ∅ | ERER | ER + ER | (ER)∗.
Semantics and Language. Next, we define the semantics of REWB via the semantic function Eλ. For a REWB E and a valuation λ from V to Σ∗, Eλ returns a set of pairs ⟨w, λ′⟩, each consisting of a matched string and an updated valuation:
ϵλ := { ⟨ϵ, λ⟩ }, σλ := { ⟨σ, λ⟩ }, ∅λ := ∅, E1E2λ := {⟨w1w2, ν⟩ : ⟨w1, µ⟩ ∈ E1λ, ⟨w2, ν⟩ ∈ E2µ}, E1 + E2λ := E1λ ∪ E2λ, E∗λ := k≥0Ekλ, where E0 := ϵ, Ek+1 := EkE, [E]xλ := {⟨w, µ[x := w]⟩ : ⟨w, µ⟩ ∈ Eλ}, \xλ := {⟨λ(x), λ⟩}.
This function is well-defined by induction on the height of Kleene stars.
Let ι be the initialized valuation that maps every variable to the empty string ϵ: i.e., ι(v) = ϵ for all v ∈ V. We simply write E to denote Eι. We define the language of a REWB E, L (E), as follows:
L (E) := {w : ⟨w, λ⟩ ∈ E}.
Pre-processing: ∅-free REWB. As a preprocessing step, we eliminate ∅ from a given REWB by repeatedly applying the following language-preserving rewrites:
E + ∅ ⇒ E, ∅ + E ⇒ E, E ∅ ⇒ ∅, ∅ E ⇒ ∅, ∅∗ ⇒ ϵ, [∅]x ⇒ ∅.
Observe that each rule strictly decreases the size (the number of symbols) of the expression. Therefore, this rewriting process always terminates.
We say that a REWB E is ∅-free if E contains no occurrence of the constant ∅. More formally, such expressions are generated by the following grammar:
E−∅ ::= ϵ | σ | E−∅ E−∅ | E−∅ + E−∅ | E−∅∗ | E−∅x | \x
Proposition 79. For every REWB E, there exists a REWB G such that L (E) = L (G) and either G is ∅-free or G = ∅.
Remark: Hereafter, we assume that the input REWB is ∅-free and not equal to ∅.
1-use REWB. Let E be a (∅-free) REWB. We call E 1-use if, in every possible computation of E, at most one backreference operation \x (for some variable x) is performed. For example,
• [(a + b)∗]x#\x is a 1-use REWB.
• [Σ∗]x\x\x is not a 1-use REWB.
• [a∗]x[b∗]y#(\x + \y) is a 1-use REWB.
• [Σ∗]x[Σ∗y]\x\y is not a 1-use REWB.
• [Σ∗]x(\x + a)(b + \x) is not a 1-use REWB.
• [Σ∗]x(a\xb)∗ is not a 1-use REWB.
To formally define the notion of 1-use, we introduce the notion of template strings.
Template String. For a given REWB expression E, we can see E as a language generator over the alphabet Γ := Σ ∪ { [, ]x, \x : x ∈ V} by treating special symbols [, ]x, and \x as usual letters. We write T(E) ⊆ Γ∗ to denote the set of template strings generated by E. Every element of T(E) is called a template string.
T(E) is formally defined as follows: We define the set of template strings T(E) ⊆ Γ∗ by structural recursion:
T(ϵ) := {ϵ}, T(σ) := {σ}, T(E1E2) := T(E1)T(E2), T(E1 + E2) := T(E1) ∪ T(E2), T(E∗) := (T(E))∗, T([E]x) := {[ w ]x : w ∈ T(E)}, T(\x) := {\x}.
For our example expression E4, T(E4) contains the following template strings for Σ = {a, b}:
T(E4) ∋ [bab]x a\xb a\xb, [abba]x a\xb a\xb a\xb, . . .
By the definition, the following properties trivially hold.
Proposition 80. Let E be an ∅-free expression. If E contains \x, then there exists s ∈ T(E) such that s contains \x. Similarly, if E has [· · · ]x, then there exists s ∈ T(E) such that s contains [· · · ]x.
Remark. Each template string can be evaluated by using •. For example,
a[bc]xd = {⟨abcd, x → bc⟩}.
From the definition and the remark, the following property of T(•) holds.
Proposition 81. Let E be a REWB. Then, the following holds:
E = T(E)
where T(E) = s∈T(E)s.
For a template string s, we write #\V(s) to denote the total number of occurrences of reference symbols \z for z ∈ V. Let #\V(E) := max{#\V(s) : s ∈ T(E)} where max ∅ = 0. Now we define 1-use REWB as follows:
REWB E is 1-use if and only if #\V(E) ≤ 1.
B.2 Normalization Overview
We aim to normalize a given 1-use REWB E into the following form:
(A1 [B1]x C1 \x D1) + (A2 [B2]x C2 \x D2) + · · · + (AK [BK]x CK\x DK) + E′
where Ai, Bi, Ci, Di, and E′ are Regexes. Here E′ represents for the 0-use (pure Regex) part.
The crucial restriction is that, in each summand, the only binding is [Bi]x and the only reference is \x, and both occur at the top level. In particular, the subexpressions Ai, Bi, Ci, and Di are pure Regexes (i.e., they contain neither bindings nor references).
To obtain our goal form, we need to solve the following tasks:
1. Lift nested reference subterms \x to the top-level in Section B.3.
2. Then, lift nested binding subterms [· · · ]x to the top-level in Section B.5.
B.3 Lifting References \x and Lemma 77
On lifting \x to the top-level, we first consider two patterns (· · · \x · · · )∗ and [· · · \x · · · ]y.
B.3.1 Handling Simple Patterns
Pattern “references in Kleene stars”: (· · · \x · · · )∗. Since our input E is 1-use, any references \x never appear inside Kleene stars. For instance, an expression [Σ∗]x(a\xb)∗ uses the variable x finitely but unboundedly many times.
Pattern “references in bindings”: [· · · \x · · · ]y. We rewrite and simplify a given 1-use REWB E so that any references \x never appear inside bindings [· · · ]y. As an example, consider an expression [Σ∗]x[a \x b]y. Since we use the variable x in the subterm a \x b, any subterms executed after this part are not allowed to use a backreference \y for any variable y. In other words, we can remove all bindings executed after a \x b. In fact, for this expression, we can safely rewrite it as follows:
[Σ∗]x[a \x b]y ⇝ [Σ∗]xa \x b
by removing [_]y.
This rewriting is accomplished by the following translation function:
unnest( [E]x ) := unnest(E) If some references appear in E, [E]x Otherwise, unnest(EF) := unnest(E)unnest(F), unnest(E + F) := unnest(E) + unnest(F), unnest(E∗) := E∗, unnest(t) := t (t ∈ {ϵ, σ} ∪ {\z : z ∈ V})
The following properties clearly hold by the definition of unnest.
Proposition 82.
(1) L (E) = L (unnest(E)) , (2) |unnest(E)| ≤ |E|.
After applying the function unnest, it suffices to consider 1-use REWBs generated by the following restricted grammar F of REWB:
F ::= ϵ | σ | F F | F + F | (F)∗ | [F]x | \x
where F is restricted to expressions that are reference-free REWBs.
B.3.2 Tagged References and Lifting References Covered by Unions
After applying unnest, our lifting phase for references is not yet complete because, in general, references may not appear at the top-level but rather be nested within unions. For instance, consider the following expression:
E := a + \x + (b \yc) + ((d∗\x) + (\xe∗))f∗.
In this example, the third and fourth reference occurrences are not at the top-level.
To lift such references, as a first step, we annotate a designated reference occurrence with a tag ρ as \xρ. This tag serves purely as a syntactic marker to distinguish this occurrence from other references. Applying this to our example E, we use ρ to generate the following set of tagged expressions:
Eρ1 : a + \xρ + (b \yc) + ((d∗\x) + (\xe∗))f∗, Eρ2 : a + \x + (b \yρc) + ((d∗\x) + (\xe∗))f∗, Eρ3 : a + \x + (b \yc) + ((d∗\xρ) + (\xe∗))f∗, Eρ4 : a + \x + (b \yc) + ((d∗\x) + (\xρe∗))f∗.
We formally define the ρ-tagging, denoted by Ξρ(E), as a function that maps an expression E to a set of expressions where exactly one reference occurrence is tagged with ρ. Let E be an expression and let Occref(E) be the list of all occurrences of reference symbols in E, ordered from left to right in the concrete syntax. Write Occref(E) = (o1, o2, . . . , oN). For each i ∈ {1, 2, . . . , N}, define Eρi to be the expression obtained from E by replacing exactly the occurrence oi of a reference symbol (say \x) with its tagged form \xρ, leaving all other symbols unchanged. Then, we define Ξρ(E) as follows:
Ξρ(E) := {Eρ1, Eρ2, . . . , EρN}
Applying this function to our example expression E, we obtain the set Ξρ(E) = {Eρ1, Eρ2, Eρ3, Eρ4}.
We naturally extend · and T(·) to accommodate the tag ρ as follows:
\xρ := \x , T( \xρ ) := { \xρ }.
To decompose the set of tagged template strings, we define two notations:
Zref(E) := {w ∈ T(E) : w does not contain any reference symbols }, T(E) ↾ref ρ := {w ∈ T(E) : w contains ρ} = T(E) \ Zref(E)
Since Zref(E) and T(E) ↾ref ρ are disjoint sets of T(E), the following basic property clearly holds.
Proposition 83. Let E be an expression and assume Ξρ(E) = Eρ1, Eρ2, . . . , EρN where N := Occref(E) is the total number of occurrences of references in E. Then, the following holds:
T(E) = Zref(E) ∪ N i=1 T(Ei) ↾ref ρ
Computing Z. Let E an expression of the grammar F. We define the function noref(E) that constructs an expression computing Zref(E).
noref(ϵ) := ϵ, noref(σ) := σ, noref(E1E2) := noref(E1)noref(E2), noref(E1 + E2) := noref(E1) + noref(E2), noref(E∗) := E∗, noref([E]x) := noref(E), noref(\x) := ∅,
By the definition, the following basic properties clearly hold.
Lemma 84.
(1) Zref(E) = T(noref(E)), (2) |noref(E)| ≤ |E|.
Computing T(E) ↾ref ρ. Let E be a REWB with a tagged reference. We define the function appearρ(E) that computes an expression computing T(E) ↾ref ρ:
appearρ(\xρ) := \xρ, appearρ(E1E2) := appearρ(E1) E2 If E1 contains ρ, E1 appearρ(E2) Else if E2 contains ρ, ∅ Otherwise, appearρ(E1 + E2) := appearρ(E1) If E1 contains ρ, appearρ(E2) Else if E2 contains ρ, ∅ Otherwise, appearρ(t) := ∅, t = ϵ, σ, \x, E∗, [E]x.
Remark: In our setting, since E∗ and [E]x never contain ρ, we set appearρ(t) = ∅ for such arguments. By the definition, the following basic property clearly holds.
Lemma 85.
T(E) ↾ref ρ = T(appearρ(E)).
Also, the following property for the form and size holds.
Proposition 86.
appearρ(E) = α \xρ β
where α and β are reference-free REWBs. Furthermore, |appearρ(E)| ≤ |E| holds. In particular, the following holds:
|α| ≤ |E|, |β| ≤ |E|.
Summary of This Section. From a given 1-use REWB E, we can construct the following:
(α1 \x1 β1) + (α2 \x2 β2) + · · · + (αK′ \xK′ βK′) + noref(E)
where αi and βi are reference-free REWBs. Also, the following holds:
K′ ≤ |E|, |αi| = O(|E|), |βj| = O(|E|), |noref(E)| = O(|E|).
This clearly corresponds our Lemma 77.
Lemma 77 (Normalizing First Step). Let E be a 1-use REWB. Then, we can decompose E into the following form:
(α1 \x D1) + (α2 \x D2) + · · · + (αK′ \x DK′) + Φ
where each αi is a reference-free (i.e., not including \y for any y) and Di and Φ are Regex rather than REWB. In particular, the following holds:
K′ ≤ |E|, |αi| = O(|E|), |Dj| = O(|E|), |Φ| = O(|E|).
B.4 Removing Unnecessary Variables and only Keeping x
For each subexpression αi \xi βi, we perform the following two translations:
1. We replace all bindings of the form [F]y (for all variables y) with F in βi.
• This replacing does not alter the expression’s behaviour because, on 1-use REWBs, any use references of the form \x do not appear in βi.
• To formally state this rewrite, we use the following function and rewrite βi ⇝ elim(βi).
elim(t) := t (t ∈ {ϵ, σ}), elim( E1E2 ) := elim( E1 )elim( E2 ), elim( E1 + E2 ) := elim( E1 ) + elim( E2 ), elim((E)∗) := elim(E)∗, elim( [E]y ) := elim( E )
2. We replace all subterms of the form [F]y (xi = y) with F in αi.
• This replacing does not alter the expression’s behaviour because we only use the variable xi and thus modifications on y are irrelevant.
• To formally state this rewrite, we use the following function and rewrite αi ⇝ keepxi(αi).
keepx(t) := t (t ∈ {ϵ, σ}), keepx( E1E2 ) := keepx( E1 )keepx( E2 ), keepx( E1 + E2 ) := keepx( E1 ) + keepx( E2 ), keepx((E)∗) := keepx(E)∗, keep[( [E]y ) := [ keepx(E) ]x If y = x, keepx(E) Otherwise.
Grammar for this Phase. We first decompose E by Proposition 83 as follows:
E ⇒ noref(E), appearρ(E1), appearρ(E2), . . . , appearρ(EN),
and for each appearρ(Ei) = αi \xi β, we rewrite it as follows:
αi \xi β ⇒ keepxi(αi) \xi elim(β).
Each expression of the form keepx(α) is generated by the following restricted grammar G:
G ::= ϵ | σ | GG | G + G | G∗ | [ G ]x.
Remark: If [· · · ]y appears in keepx(α), then y = x must hold.
Hereafter, we translate an expression α of G into the following language-equivalent form:
α ⇒ A [B]x C
where A, B, and C are pure REGEX.
B.5 Lift Bindings to the Top level and Lemma 78
In moving all occurrences of binding to the top-level, we handle two patterns: [· · · [F]x · · · ]x and (· · · [F]x · · · )∗.
B.5.1 Pattern [· · · [F]x · · · ]x
For instance, consider the expression [a [Σ∗]x b]x. Since only the last modification to the variable x is effective, we can rewrite the expression to [a Σ∗ b]x without changing its behaviour.
unnest2( [E]x ) := [ elim(E) ]x, unnest2(EF) := unnest2(E)unnest2(F), unnest2(E + F) := unnest2(E) + unnest2(F), unnest2(E∗) := (unnest2(E))∗, unnest2(t) := t (t ∈ {ϵ, σ})
By the definition, the following basic properties trivially hold.
Proposition 87. The following properties hold for unnest2.
(1) L (E) = L (unnest2(E)) , (2) |unnest2(E)| ≤ |E|.
After this translation, we can further restrict our grammar to the following form:
H ::= ϵ | σ | HH | H + H | H∗ | [REGEX]x.
B.5.2 Pattern (· · · [F]x · · · )∗
Handling this pattern is the most elaborate part in our normalization procedure.
Tagged Binding.
We annotate a designated binding occurrence with a tag ρ by writing it as [E]ρx. The tag serves only as a syntactic marker to distinguish this occurrence from other bindings.
For instance, let us consider the following expression:
E := (a + [b∗]x + (c [d∗]xe)∗ )∗.
To handle each binding subterm separately, we use ρ as follows and generate two tagged expressions from the above one:
Eρ1 : (a + [b∗]ρx + (c [d∗]xe)∗ )∗ , Eρ2 : (a + [b∗]x + (c [d∗]ρx e)∗ )∗ .
Similar to tagging references, we write Occbind(E) to denote the total number of bind occurrences in E and Ξ′(E) to denote the set of expressions where exactly one binding occurrence is tagged with ρ.
We naturally extend ·, T(·), and elim to accommodate the tag ρ as follows:
[E]ρx := [E]x , T( [E]ρx ) := [ T(E) ]ρx = { [ w ]ρx : w ∈ T(E)}, elim( [E]ρx ) := elim( E ).
For a tagged expression E, we write T(E) ↾ ρ to denote the following set:
T(E) ↾bind ρ := {w ∈ T(E) : w contains a substring of the form [· · · ]ρx at least once }.
Decomposition by the last tag
For a template string s, we write lastρ(s) if both the following conditions hold:
• s contain some binding occurrences.
• Furthermore, its last binding occurrence is of the form [· · · ]ρx.
Now we write Zρbind(α) to denote the set of template strings generated by α that contains no binding symbols:
Zρbind(α) := T(E) \ (T(E) ↾bind ρ) = {w ∈ T(α) : w does not contain any binding occurrnces}.
Now we define the following notation to denote the set of template strings generated by E whose last modifier is tagged by ρ:
T(E) ⇑ ρ := {s ∈ T(E) ↾bind ρ : lastρ(s)}.
As with Proposition 83, the following decomposition clearly holds.
Proposition 88. Let E be an expression of the grammar H. Assume Ξ′(E) = Eρ1, Eρ2, . . . , EρN where N := Occbind(E) is the total number of occurrences of binding in E. Then, the following holds:
T(E) = Zρbind(E) ∪ N i=1 T(Ei) ⇑ ρ
Hereafter, for each Ei, we compute an expression of the form Ai [Bi]ρx Ci such that
• T(Ei) ⇑ ρ = Ai [Bi]ρx Ci; and
• Ai, Bi, Ci are pure Regexes.
Computing Z. Let E be an expression of H. We define the function nobind(E) that computes an expression computing Z(E).
nobind(ϵ) := ϵ, nobind(σ) := σ, nobind( E1E2 ) := nobind( E1 )nobind( E2 ), nobind( E1 + E2 ) := nobind( E1 ) + nobind( E2 ), nobind((E)∗) := nobind(E)∗, nobind( [E]x ) := ∅, nobind( [E]ρx ) := ∅,
By the definition, the following properties clearly hold for nobind.
Proposition 89.
(1) Zρbind(E) = nobind(E), (2) |nobind(E)| ≤ |E|.
Strategy for Representing the Part T(Ei) ⇑ ρ
To explain our idea, let us consider the following expression:
(ab + c[Σ∗]xd + e[Σ∗]xf)∗
where Σ = {a, b, c, d}. By tagging, we obtain the following two expressions:
Eρ1 : (ab + c[Σ∗]ρxd + e[Σ∗]xf)∗, Eρ2 : (ab + c[Σ∗]xd + e[Σ∗]ρxf)∗.
We here consider Eρ1 and write E to denote the subterm (ab + c[Σ∗]ρxd + e[Σ∗]xf).
Our key idea is to unfold Kleene stars E∗ so that the following holds:
T( E∗ ) ⇑ ρ = repeating E · running E guaranteed to visit the [· · · ]ρx part exactly once · repeating E while never visiting any [· · · ]x subterms (corresponds to nobind(E)∗).
For our example, we unfold E∗ as follows
E∗ · c[Σ∗]ρxd · (ab)∗ .
Using the single-underlined and double-underlined parts, we enforce that ρ appears as the last occurrence of binding across the entire computation of E∗.
Furthermore, in this form, we can remove [· · · ]x from the E∗ because the single-underlined part overwrites the variable x. Namely, it suffices to consider the following expression:
E′ := elim(E)∗ · c[Σ∗]ρxd · (ab)∗ = ab + c Σ∗ d + e Σ∗ f∗ c [Σ∗]ρx d (ab)∗ .
The transformed expression fits into our goal form A[B]xC.
To compare T(E∗) and T(E′), we consider the following template string generated by E∗:
w := ab c [ac]ρx d e [aaaa]x f c [a]ρx d ababab ∈ T(E∗).
Since this string contains ρ as the last binding occurrence, it is represented in our transformed version E′ by discarding binding symbols before the last ρ as follows:
w′ := ab c ac d e aaaa f c [a]ρx d ababab ∈ T(E′).
Furthermore, w = w′ clearly holds.
Formalizing Our Translation
To compute T(E) ⇑ ρ on the basis of the above our idea, we introduce the following function lastρ so that T(E) ⇑ ρ = lastρ(E):
lastρ(ϵ) := ∅, lastρ(σ) := ∅, lastρ(E1E2) := lastρ(E1) nobind(E2) If E1 contains ρ, elim(E1) lastρ(E2) Otherwise (since ρ is unique and in E, it must be in E2), lastρ(E1 + E2) := lastρ(E1) If E1 contains ρ, lastρ(E2) Otherwise: E2 contains ρ, lastρ( (E)∗ ) := elim(E)∗ lastρ(E) nobind(E)∗, lastρ([E]x) := ∅, lastρ([E]ρx) := [E]ρx.
Remark: The argument expressions E of lastρ satisfy the following condition:
1. Since E ∈ H, the expression is reference-free, i.e., it contains no reference/usage symbols of the form \z;
2. and moreover, every binding occurrence binds the same variable x, i.e., every binder is of the form [·]x or [·]ρx
3. Also, since E ∈ H, every binding occurrence is of the form [R]x (and, for tagged expressions, [R]ρx) with R a pure Regex. In particular, binders are never nested, i.e., no binder occurs within the scope of another binder.
4. Since E is an element of the set of tagged expressions Ξ′, the tag ρ is syntactically unique, i.e., there is exactly one tagged binding occurrence of the form [·]ρx in the expression.
Then, the following property holds for lastρ.
Lemma 90. Let E be an expression that satisfies the conditions in the above remark. Then, the following holds:
T(E) ⇑ ρ = lastρ(E).
In particular, the generated expression lastρ(E) satisfies the following condition.
Proposition 91. Let E be an expression that satisfies the conditions in the above remark. Then, lastρ(E) evaluates to an expression of the form A [B]ρx C where A, B, and C are pure Regex. Furthermore,
|A| = O(|E|2), |B| ≤ |E|, |C| = O(|E|2).
Proof. By definition, elim and nobind erase all binding constructs and thus always produce Regexes. Moreover, lastρ never introduces new binders: untagged binders are discarded (lastρ([F]x) = ∅), while the unique tagged binder is preserved (lastρ([F]ρx) = [F]ρx). Since binders are not nested and ρ is syntactically unique, the expression lastρ(E) contains exactly one binder, namely the tagged one, and hence can be written as A[B]ρxC with A, B, C pure Regexes.
To show the size bound, we use the following trivial properties, which are immediately shown by the definition of elim and nobind:
for every expression E, |elim(E)| ≤ |E|, |nobind(E)| ≤ |E|.
To perform our induction, we consider a spine of subexpressions starting from E as follows. Consider the syntax tree of the input expression E and follow the unique path from the root to the unique tagged binder. This yields a chain of subexpressions
E = E0 ≻ E1 ≻ · · · ≻ Eh = [B]ρx,
where X ≻ Y means that Y is a proper subexpression of X. Thus, Ei+1 is the unique immediate subexpression of Ei that still contains the tag ρ. Here, the existence and uniqueness follow from the syntactic uniqueness of ρ.
Induction on the length of the spine. We need to consider four cases: Ei = Ei+1 + F, Ei = Ei+1F, Ei = FEi+1, and Ei = (Ei+1)∗. For these cases, each step from Ei+1 to Ei modifies the prefix/suffix by concatenating at most one extra piece whose size is O(|Ei|): either elim(F)•, or •nobind(F), or elim(Ei+1)∗ • nobind(Ei+1)∗. Consequently,
|Ai| ≤ |Ai+1| + O(|Ei|), |Ci| ≤ |Ci+1| + O(|Ei|).
Unrolling from i = h − 1, h − 2, . . . , 0, we have
|A0| = O h−1 i=0 |Ei| , |C0| = O h−1 i=0 |Ei| .
Finally, along a strict subexpression chain, we have |E0| > |E1| > · · · > |Eh| ≥ 1, hence
h−1 i=0 |Ei| ≤ |E| + (|E| − 1) + · · · + 1 = O(|E|2).
Therefore |A| = |A0| = O(|E|2) and |C| = |C0| = O(|E|2), and we already noted |B| ≤ |E|.
Now, summarizing all the objectives up to this point, we immediately prove Lemma 78.
Lemma 78 (Normalizing Second Step). Let α be an expression of the restricted grammar H. Then, we can decompose α into the following form:
(A1 [B1]x C1) + (A2 [B2]x C2) + · · · + (AK′′ [BK′′]x CK′′) + Ψ,
where Ai, Bi, Ci, and Ψ are Regexes.
In particular, the following holds for each expression size:
K′′ ≤ |E|, |Ai| = O(|E|2), |Bi| ≤ |E|, |Ci| = O(|E|2), |Ψ| ≤ |E|.
C Analyzing Hidden Constants
In this section, we analyze the hidden constants of our theorems. We mainly consider the constant of Theorem 7. We first obtain a bound of 2O((|A|+|B|+|C|+|D|)4) by using the fact that any Regex E admits a transition monoid of size 2O(|E|2). We then refine this bound to 2O((|A|+|B|+|C|+|D|)2) through a more fine-grained analysis combined with additional data structures.
C.1 First Bound for Theorem 7: 2O((|A|+|B|+|C|+|D|)4)
We first observe that the time complexity of all parts of our algorithm depends polynomially on the size of the transition monoids we use.
Interval evaluation by factorization forest. In our algorithm, we repeatedly perform the operations of evaluating ∆E(w[i .. j)) for E ∈ {A, B, C, D}. By Lemma 18, it takes O(|TE|) time, which only increases the time complexity polynomially in |TE|. Thus, from now on, we focus on the remaining part and ignore the complexity of evaluating ∆E(w[i, j)).
Section 6. The time complexity of this part depends polynomially on the size of the representation of the ultimately periodic set S = SX + (2 · SY) + SZ. By a similar argument to that in the proof of Lemma 46, we can state that the parameters µ and λ of SX, SY, and SZ are bounded by |TX|, |TY|, and |TZ|, respectively. Thus, the parameters of S are bounded by a polynomial in |TX| + |TY| + |TZ|.
Section 7. It is easy to see that this part affects the hidden constant only by |KL| + |KR| in Algorithm 1, which are bounded by O(|TC|).
Section 8. This part contributes a factor polynomial in |Λ|, |Accum|, and |TD| to the hidden constant in Algorithm 2. Since |Λ| ≤ |TD|, this part affects the hidden constant by a polynomial in |TC| + |TD|.
Section 9. It is not difficult to see that each method in this part runs in time proportional to the depth of the factorization forest FF and the size of TC. Since the depth of FF is O(|TC|), each method runs in O(|TC|2) time.
Section 10. It is easy to see that this part affects the hidden constant only by |D| in Algorithm 4 and |D1| + |D2| in Algorithm 5, which are bounded by O(|TC|).
Section 11. By the same argument as in Section 9, each method runs in O(|TC|2) time.
Section 12. The time complexity of this part depends polynomially on |TC| and the size of the representation of the ultimately periodic set Sδ = SA + SC,δ. By a similar argument to that in the proof of Lemma 46, we can state that the parameters µ and λ of SA and SC,δ are bounded by |TA| and |TC|, respectively. Thus, the parameters of S are bounded by a polynomial in |TA| + |TC|.
Overhead of normalization. We have established that the hidden constant depends polynomially on |TA| + |TB| + |TC| + |TD|, where Regexes A, B, C, D are those defined in Sections 4 and 5. We complete the analysis by seeing that each of those Regexes, which we refer to as A′, B′, C′, D′ to distinguish them from the original Regexes, has length linear in the size of the original Regexes A, B, C, D.
The operations in Section 4 multiply the length of each Regex by O(log |Σ|), which we consider to be an absolute constant7. Moreover, in Section 5, we defined
7In fact, we can avoid the dependence on log |Σ| here by not binarizing the Regexes. This requires additional care in later sections, as the suffix tree is no longer binary; nevertheless, it is still possible to obtain the same bound for general |Σ|. For the sake of simplicity of presentation, we refrained from implementing this approach.
L B′ := (L (B) \ {ϵ}) · L Cq0C→{qC} ∩ L Dq0D→{qD}
for some qC ∈ QC and qD ∈ QD, and
L A′ := L (A) , L C′ := L C{qC}→FC , L D′ := L D{qD}→FD ,
for some qC ∈ QC and qD ∈ QD.
Clearly, the NFAs for A′, C′, and D′ have the same number of vertices as the NFAs for A, C, and D, respectively. Thus, we can construct transition monoids TA′, TC′, and T′D of size 2O(|A|2), 2O(|C|2), and 2O(|D|2), respectively. For B′, straightforward construction yields a transition monoid TB′ of size 2O((|B|+|C||D|)2) because, using the standard construction, the NFA for B′ has size O(|B| + |C||D|). Therefore, |TA′| + |TB′| + |TC′| + |TD′| ≤ 2O(|A|2) + 2O((|B|+|C||D|)2) + 2O(|C|2) + 2O(|D|2) ≤ 2O((|A|+|B|+|C|+|D|)4). Thus, the overall hidden constant is 2O((|A|+|B|+|C|+|D|)4).
C.2 Refined Bound for Theorem 7: 2O((|A|+|B|+|C|+|D|)2)
The main obstacle to achieving a running time of 2O((|A|+|B|+|C|+|D|)2) is that the size of the NFA for B′ is quadratic. If this size could be reduced to linear in the size of original Regexes, the desired bound would follow immediately; however, this appears to be difficult.
Instead, we observe that the algorithm accesses the transition monoid TB′ only in very restricted situations. More precisely, the only operations we perform with respect to B′ are:
• the construction of an ultimately periodic set S in Section 6 (note that Y = B′), and
• deciding whether w[i .. j) ∈ L (B′) (Algorithms 2 and 4).
Bounding the Size of S (Section 6). In Section 6, we need to decide whether e ∈ S = SX + (2 · SY) + SZ. Previously, we bounded the size of the representation of SY by |TB′| ≤ 2O((|B|+|C||D|)2), which resulted in a large hidden constant. However, we can show that the size of
SY = {j : θj ∈ L (Y)}
is in fact only 2O(|B|+|C||D|).
To see this, let NB′ = (QB, Σ, ∆B, EB, q0B, FB) be an ϵ-NFA recognizing L (B′). For each j ≥ 0, let Rj ⊆ QB denote the set of states reachable from q0B by reading θj. Then, by a similar argument to that in the proof of Lemma 46, Rj+λ = Rj holds for all j ≥ µ, where µ, λ ≤ |QB|. Consequently, the ultimately periodic set
SY = {j : Rj ∩ FB = ∅}
admits a representation of size 2|QB| ≤ 2O(|B|+|C||D|), and thus, S admits a representation of size 2O((|A|+|B|+|C|+|D|)2).
Reducing the Hidden Constant of Interval Evaluation. By Lemma 18, interval evaluation over TB′ runs in O(|TB′|) ≤ 2O((|B|+|C||D|)2) time, which again yields a large hidden constant. However, this part is not a bottleneck with respect to |w|, since the algorithm performs interval evaluation over TB′ only O(|w| log |w|) times in total; O(|w|) times in the branching ABCBD problem and O(|w| log |w|) times in the XYYZ problem when computing the set SY.
We therefore replace this procedure with a data structure that answers each query in O(log |w|) time while having a significantly smaller hidden constant. We employ a segment tree, which can be viewed as a factorization forest without idempotent nodes, but with height O(log |w|) independent of the monoid size.
Let NB′ = (QB, Σ, ∆B, EB, q0B, FB) be an ϵ-NFA recognizing L (B′). Each node of the segment tree corresponding to an interval [ℓ, r) stores a binary matrix M ∈ 2QB×QB, where Mq1,q2 = 1 if and only if there exists a path from q1 to q2 labeled by w[ℓ .. r). Matrix multiplication is defined via (∨, ∧)-convolution.
For any interval query [i, j), by the standard argument, we can compute a binary matrix Mi,j ∈ 2QB×QB satisfying Mi,jq1,q2 = 1 if and only if there exists a path from q1 to q2 labeled by w[i .. j), in time O(|QB|3 log |w|). Finally, we can decide whether w[i .. j) ∈ L (B′) by checking whether there exists a state q2 ∈ FB such that Mi,jq0B,q2 = 1. Thus, we can implement this part in a way that it contributes only O((|B| + |C||D|)3|w| log |w|) to the total time complexity.
C.3 Bound for Theorem 8
Observe that, in the construction in Appendix B, the lengths |A|, |B|, |C|, |D| are at most O(|E|2), O(|E|), O(|E|2), and O(|E|), respectively, for the input REWB E. Combining with the discussion in the previous part, the hidden constant of Theorem 8 is O(2|E|4).
C.4 Bound for Theorem 9
By a similar argument to the one above, we obtain a hidden constant of 2O((|X|+|Y|+|Z|)2) + 2O(|X|+|Y|+|Z|) · α for our O(|w| log |w|)-time algorithm in Theorem 9. The term 2O((|X|+|Y|+|Z|)2) arises from the computation of the set SX, SY, and SZ, where each computation requires O(|w| log |w|) interval evaluations on the factorization forest. 2O(|X|+|Y|+|Z|) · α part is from the computation of the representation of the set S.
We see that if we allow an additional O(log |w|) factor on the dependence on |w|, we can reduce the hidden constant to a polynomial. As discussed above, for interval evaluation, we adopt a segment tree instead of a factorization forest; this works in O(poly(|X| + |Y| + |Z|) log |w|) time.
The remaining task is to determine whether e ∈ S = SX + (α · SY) + SZ. Instead of computing the representation of S, we decide whether e ∈ S directly. For an ϵ-NFA N = (Q, Σ, ∆, E, q0, F) and a string θ, let N(θ) := (Q, {θ}, ∆(θ), ∅, q0, F) be an NFA over the unary alphabet {θ}, where ∆(θ) is defined by
{(p, θ, q) : q can be reached from p by reading θ in N}.
Let NX = (QX, Σ, ∆X, EX, q0X, FX) be the ϵ-NFA for X. Define NY and NZ similarly. We define
N′X := {Nq→FXX(θ) : q is reachable from q0X by reading w1}.
Let N′Y be the NFA obtained from Nq0Y→FYY(θ) by subdividing each edge into α segments, and let N′Z := Nq0Z→FZ(θ), where F is the set of states q such that FZ is reachable from q by reading w2.
Then, for each N′X ∈ N′X, we construct an ϵ-NFA Nall by connecting all accepting states of N′X to the initial state of N′Y, and all accepting states of N′Y to the initial state of N′Z. The initial state and the accepting states of Nall are the initial state of N′X and the accepting states of N′Z, respectively. Now, we can claim that e is in S if and only if Nall accepts the length-e string, or equivalently, there is a walk of length e + 2 from the initial state to an accepting state of Nall. This can be determined in O(|Nall|3 log e) time by standard matrix powering. Thus, the whole algorithm runs in O(poly(|X| + |Y| + |Z|)|w| log2 |w|) time.