Counting on General Run-Length Grammars
Abstract
We introduce a data structure for counting pattern occurrences in texts compressed with any run-length context-free grammar. Our structure uses space proportional to the grammar size and counts the occurrences of a pattern of length in a text of length in time , for any constant chosen at indexing time. This is the first solution to an open problem posed by Christiansen et al. [ACM TALG 2020] and enhances our abilities for computation over compressed data; we give an example application.
Keywords and phrases:
Grammar-based indexing, Run-length context-free grammars, Counting pattern occurrences, Periods in stringsFunding:
Gonzalo Navarro: Funded by Basal Funds FB0001 and AFB240001, Mideplan, Chile, and Fondecyt Grant 1-230755, Chile.Copyright and License:
![[Uncaptioned image]](x1.png)
2012 ACM Subject Classification:
Theory of computation Data structures design and analysisAcknowledgements:
We thank the reviewers for their comments, particularly one that did an exhaustive and thoughtful job to improve our presentation.Editors:
Paola Bonizzoni and Veli MäkinenSeries and Publisher:

1 Introduction
Context-free grammars (CFGs) have proven to be an elegant and efficient model for data compression. The idea of grammar-based compression [51, 29] is, given a text , to construct a context-free grammar of size that only generates . One can then store instead of , which achieves compression if . Compared to more powerful compression methods like Lempel-Ziv [35], grammar compression offers efficient direct access to arbitrary snippets of without the need of full decompression [49, 3]. This has been extended to offering indexed searches (i.e., in time ) for the occurrences of string patterns in [8, 16, 10, 7, 40], as well as more complex computations over the compressed sequence [32, 21, 18, 19, 41, 28]. Since finding the smallest grammar representing a given text is NP-hard [49, 5], many algorithms have been proposed to find small grammars for a given text [34, 49, 46, 50, 36, 23, 24]. Grammar compression is particularly effective when handling repetitive texts; indeed, the size of the smallest grammar representing is used as a measure of its repetitiveness [39].
Nishimoto et al. [47] proposed enhancing CFGs with “run-length rules” to improve the compression of repetitive strings. These run-length rules have the form , where is a terminal or a non-terminal symbol and is an integer. CFGs that may use run-length rules are called run-length context-free grammars (RLCFGs). Because CFGs are RLCFGs, the size of the smallest RLCFG generating always satisfies , and it can be in text families as simple as , where and .
The use of run-length rules has become essential to produce grammars with size guarantees and convenient regularities that speed up indexed searches and other computations [32, 21, 18, 7, 28, 30]. The progress made in indexing texts with CFGs has been extended to RLCFGs, reaching the same status in most cases. These functionalities include extracting substrings, computing substring summaries, and locating all the occurrences of a pattern string [7, App. A]. It has also been shown that RLCFGs can be balanced [42] in the same way as CFGs [19], which simplifies many compressed computations on RLCFGs.
Interestingly, counting, that is, determining how many times a pattern occurs in the text without spending the time to list those occurrences, can be done efficiently on CFGs, but not so far on RLCFGs. Counting is useful in various fields, such as pattern discovery and ranked retrieval, for example to help determine the frequency or relevance of a pattern in the texts of a collection [37].
Navarro [44] showed how to count the occurrences of a pattern in in time using space if a CFG of size represents , for any constant chosen at indexing time. Christiansen et al. improved this time to by using more recent underlying data structures for tries. Christiansen et al. [7] and Kociumaka et al. [30] extended the result to particular RLCFGs, even achieving optimal time by using additional space, but could not extend their mechanism to general RLCFGs. Their paper [7] finishes, referring to counting, with “However, this holds only for CFGs. Run-length rules introduce significant challenges […] An interesting open problem is to generalize this solution to arbitrary RLCFGs.”
In this paper we give the first solution to this open problem, by introducing an index that counts the occurrences of a pattern in a text represented by a RLCFG of size . Our index uses space and answers queries in time for any constant chosen at indexing time. This is the same time complexity that holds for CFGs, which puts on par our capabilities to handle RLCFGs and CFGs on all the considered functionalities. As an example of our new capabilities, we show how a recent result on finding the maximal exact matches of using CFGs [45] can now run on RLCFGs.
While our solution builds on the ideas developed for CFGs and particular RLCFGs [44, 7, 30], arbitrary RLCFGs lack crucial structure that holds in those particular cases, namely that if there exists a run-length rule , then the period [11] of the string represented by is the length of that of . We show, however, that the general case still retains some structure relating the shortest periods of and the string represented by . We exploit this relation to develop a solution that, while considerably more complex than that for those particular cases, retains the same theoretical guarantees obtained for CFGs.
2 Basic Concepts
2.1 Strings
A string is a sequence of symbols, where each symbol belongs to a finite ordered set of integers called an alphabet . The length of is denoted by . We denote with the empty string, where . A substring of is (which is if ). A prefix (suffix) is a substring of the form (); we also say that () prefixes (suffixes) . We write if prefixes , and if in addition ( strictly prefixes ).
We denote with the concatenation of and . A power of a string , written , is the concatenation of copies of . The reverse string of refers to . We also use the term text to refer to a string.
2.2 Periods of strings
Periods of strings [11] are crucial in this paper. We recall their definition(s) and a key property, the renowned Periodicity Lemma.
Definition 1.
A string has a period if, equivalently,
-
1.
it consists of consecutive copies of plus a (possibly empty) prefix of , that is, ; or
-
2.
; or
-
3.
for all .
We also say that is a period of . We define as the shortest period of a non-empty string and say is periodic if .
Lemma 2 ([14]).
If and are periods of and , then is a period of . Thus, divides all other periods of .
2.3 Karp-Rabin signatures
Karp–Rabin [26] fingerprinting assigns a function to the string , where is a suitable integer and a prime number. Bille et al. [4] showed how to build, in expected time, a Karp–Rabin signature built from a pair of Karp–Rabin functions, which has no collisions between substrings of . We always assume those kind of signatures in this paper.
A well-known property is that we can compute the functions for all the prefixes in time , and then obtain any function (and, consequently, any signature ) in constant time by using arithmetic operations.
2.4 Range summary queries on grids
A discrete grid of rows and columns stores points at integer coordinates , with and . Grids with points can be stored in space, so that some summary queries are performed on orthogonal ranges of the grid. In particular, one can associate an integer with each point, and then, given an orthogonal range , compute the sum of all the integers associated with the points in that range. Chazelle [6] showed how to run that query in time , for any constant , in space, which works for any semigroup. Navarro [44] describes a simpler solution for groups.
2.5 Grammar compression and parse trees
A context-free grammar (CFG) is a language generation model consisting of a finite set of nonterminal symbols and a finite set of terminal symbols , disjoint from . The set contains a finite set of production rules , where is a nonterminal symbol and is a string of terminal and nonterminal symbols. The language generation process starts from a sequence formed by just the nonterminal and, iteratively, chooses a rule and replaces an occurrence of in the sequence by , until the sequence contains only terminals. The size of the grammar, , is the sum of the lengths of the right-hand sides of the rules, . Given a string , we can build a CFG that generates only . Then, especially if is repetitive, is a compressed representation of . The expansion of a nonterminal is the string generated by , for instance ; for terminals we also say . We use and .
The parse tree of a grammar is an ordinal labeled tree where the root is labeled with the initial symbol , the leaves are labeled with terminal symbols, and internal nodes are labeled with nonterminals. If , with , then a node labeled has children labeled, left to right, . A more compact version of the parse tree is the grammar tree, which is obtained by pruning the parse tree such that only one internal node labeled is kept for each nonterminal , while the rest become leaves. Unlike the parse tree, the grammar tree of has only nodes. Consequently, the text can be divided into at most substrings, called phrases, each being the expansion of a grammar tree leaf. The starting phrase positions constitute a string attractor of the text [27]. Therefore, all text substrings of length more than 1 have at least one occurrence that crosses a phrase boundary.
2.6 Run-length grammars
Run-length CFGs (RLCFGs) [47] extend CFGs by allowing in rules of the form , where is an integer and is a string of terminals and nonterminals. These rules are equivalent to rules with repetitions of . However, the length of the right-hand side of the rule is defined as , not . To simplify, we will only allow run-length rules of the form , where is a single terminal or nonterminal; this does not increase the asymptotic grammar size because we can rewrite and for a fresh .
RLCFGs are never larger than general CFGs, and they can be asymptotically smaller. For example, the size of the smallest RLCFG that generates is in , where is a measure of repetitiveness based on substring complexity [48, 31], but such a bound does not always hold for the size of the smallest grammar. The maximum stretch between and is , as we can replace each rule by CFG rules.
We denote the size of an RLCFG as . To maintain the invariant that the grammar tree has nodes, we represent rules as a node labeled with two children: the first is and the second is a special leaf , denoting repetitions of .
3 Grammar Indexing for Locating
A grammar index represents a text using a grammar that generates only . As opposed to mere compression, the index supports three primary pattern-matching queries: locate (returning all positions of a pattern in the text), count (returning the number of times a pattern appears in the text), and extract (extracting any desired substring of ). In order to locate, grammar indexes identify “initial” pattern occurrences and then track their “copies” throughout the text. The former are the primary occurrences, defined as those that cross phrase boundaries, and the latter are the secondary occurrences, which are confined to a single phrase. This approach [25] forms the basis of most grammar indexes [8, 9, 10] and related ones [16, 33, 12, 17, 13, 2, 43, 52], which first locate the primary occurrences and then derive their secondary occurrences through the grammar tree.
As mentioned in Section 2.5, the grammar tree leaves cut the text into phrases. In order to report each primary occurrence of a pattern exactly once, let be the lowest common ancestor of the first and last leaves the occurrence spans; is called the locus node of the occurrence. Let have children and the first leaf that covers the occurrence descend from the th child of . If represents , it follows that finishes with a pattern prefix and that starts with the suffix . We will denote such cuts as . The alignment of within is the only possible one for that primary occurrence.
Following the original scheme [25], grammar indexing builds two sets of strings, and , to find primary occurrences [8, 9, 10]. For each grammar rule , the set contains all the reverse expansions of the children of , , and contains all the expansions of the nonempty rule suffixes, . Both sets are sorted lexicographically and placed on a grid with (less than) points, for each rule . Given a pattern , for each cut , we first find the lexicographic ranges of in and of in . Each point represents a primary occurrence of . Grid points are augmented with their locus node and offset . The cut-based approach naturally extends to the case by allowing empty prefixes, that is, cuts of the form . We then search for suffixes matching in , combining them with all rows in to retrieve all primary occurrences of the character.
Once we identify the locus node (with label ) of a primary occurrence, every other mention of or its ancestors in the grammar tree, and recursively, of the ancestors of those mentions, yields a secondary occurrence of . Those are efficiently tracked and reported [9, 10, 7]. An important consistency observation for counting is that the amount of secondary occurrences triggered by each primary occurrence is fixed. See Figure 1.
The original approach [9, 10] spends time to find the ranges and for the cuts of ; this was later improved to [7]. Each primary occurrence found in the grid ranges takes time using geometric data structures, whereas each secondary occurrence requires time. Overall, the occurrences of in are listed in time .
To generalize this solution to RLCFGs [7, App. A.4], rules are added as a point in the grid. This suffices to capture every primary occurrence of the corresponding rule : If there are primary occurrences with the cut in , then one is aligned with the first phrase boundary, . Precisely, there is space to place right after the first phrase boundaries. When the point is retrieved for a given cut, then, primary occurrences are declared with offsets , , , within . The amount of secondary occurrences triggered by each such primary occurrence still depends only on .
4 Counting with Grammars
Navarro [44] obtained the first result in counting the number of occurrences of a pattern in a text represented by a CFG of size , within time , for any constant , and using space. His method relies on the consistency observation above, which allows enhancing the grid described in Section 3 with the number of (primary and) secondary occurrences associated with each point. At query time, for each pattern cut, one sums the number of occurrences in the corresponding grid range using the technique mentioned in Section 2.4. The final complexity is obtained by aggregating over all cuts of and considering the time required to identify all the ranges. Christiansen et al. [7, Thm. A.5] later improved this time to just , by using more modern techniques to find the grid range of all cuts of .
Christiansen et al. [7] also presented a method to count in time on a particular RLCFG of size , where is the size of the smallest string attractor [27] of . They also show that by increasing the space to one can reach the optimal counting time, . The grammar properties allow reducing the number of cuts of to check to , instead of the cuts used on general RLCFGs.
Christiansen et al. build on the same idea of enhancing the grid with the number of secondary occurrences, but the process is considerably more complex on RLCFGs, because the consistency property exploited by Navarro [44] does not hold on run-length rules : the number of occurrences triggered by a primary occurrence with cut found from the point depends on , , and . Their counting approach relies on another property that is specific of their RLCFG [7, Lem. 7.2]:
Property 1.
For every run-length rule , the shortest period of is .
This property facilitates the division of the counting process into two cases. For each run-length rule , they introduce two points, and , in the grid. These points are associated with the values and , respectively. The counting process is as follows: for a cut where is a suffix of , if , then it will be counted times, as both points will be within the search range. If instead exceeds , but still , then it will be counted times, solely by point . Finally if exceeds , then is periodic (with ).
They handle that remaining case as follows. Given a cut and the period , where , the number of primary occurrences of this cut inside rule is (cf. the end of Section 3). Let be the set of rules such that is a suffix of and is a prefix of , that is, those within the grid range of the cut, and the number of (primary and secondary) occurrences of . Then, the number of occurrences triggered by the primary occurrences found within symbols in for this cut is
(1) |
For each run-length rule , they compute a Karp–Rabin signature (Section 2.3) and store it in a perfect hash table [15, 1], associated with values
Additionally, for each such , the authors store the set .
At query time, they calculate the shortest period . For each cut , is periodic if . If so, they compute , and if there is an entry associated with in the hash table, they add to the number of occurrences found up to then
(2) |
where is computed using exponential search over in time. Note that they exploit the fact that the number of repetitions to subtract, , depends only on , and not on the exponent of rules .
Since fingerprints are collision-free on substrings of , and the nonterminals in their particular RLSLP produce distinct expansions, each valid fingerprint corresponds to at most one nonterminal . This guarantees that, if a match is found in the hash table, it uniquely identifies a single candidate . Further, they show how to filter out false positives for prefixes of that do not occur in the set [7, Lem. 6.5].
The total counting time, on a grammar of size , is . In their grammar, the number of cuts to consider is , which allows reducing the cost of computing the grid ranges to . The signatures of all substrings of are also computed in time, as mentioned in Section 2.3. Considering the grid searches, the total cost for counting the pattern occurrences drops to [7, Sec. 7].
5 Our Solution
We now describe a solution to count the occurrences in arbitrary RLCFGs, where the convenient Property 1 used in the literature may not hold. We start with a simple observation.
Lemma 3.
Let be a rule in a RLCFG. Then divides .
Proof.
Clearly is a period of because . By Lemma 2, then, since , divides .
Some parts of our solution make use of the shortest period of . We now define some related notation.
Definition 4.
Given a rule with , let (which divides by Lemma 3). The corresponding transformed rule is , where is a new nonterminal such that , and .
There seems to be no way to just transform all run-length rules (which would satisfy Property 1, ) without blowing up the RLCFG size by a logarithmic factor. We will use another approach instead. We classify the rules into two categories.
Definition 5.
Given a rule with , we say that is of type-E (for Equal) if ; otherwise, and we say that A is of type-L (for Less).
We build on Navarro’s solution [44] for counting on CFGs, which uses an enhanced grid where points count all the occurrences they trigger. The grid ranges are found with the more recent technique [7] that takes time. Further, we treat type-E rules exactly as Christiansen et al. [7] handle the run-length rules in their specific RLCFGs, as described in Section 4. This is possible because type-E rules, by definition, satisfy Property 1. Their method, however, assumes that no two symbols have the same expansion. To relax this assumption, symbols with the same expansion should collectively contribute to the same entries of and . We thus index those tables using rather than , and for simplicity write , , and , where . Further, the time to filter our false positives using their Lemma 6.5 [7] is because we must explore all the cuts of .
Since each primary occurrence is found in exactly one rule, we can decompose the process of counting by adding up the occurrences found inside type-E and type-L rules. We are then left with the more complicated problem of counting occurrences found from type-L rules. We start with another observation.
Observation 6.
If is a type-L rule, then
Proof.
If is a type-L rule then . In addition, by Lemma 3, divides . Therefore
For type-L rules, we will generalize the strategy of Section 4: the cases where will be handled by adding points to the enhanced grid; in the other cases we will use new data structures that exploit the fact (to be proved) that is periodic. Note that each cut may correspond to different cases for different run-length rules, so our technique will consider all the cases for each cut. Although the primary occurrences within a rule will still be defined as those that cross boundaries of , we will find them by aligning (all the possible) cuts with the boundaries of the nonterminals of the transformed rules . The following definition will help us show how we capture every primary occurrence exactly once.
Definition 7.
The alignment of a primary occurrence found with cut inside the type-L rule is .
The definition is sound because every primary occurrence is found using exactly one cut . Note that is the distance from the starting position of an occurrence, within , to the start of the next copy of . We will explore all the possible cuts of , but each rule will be probed only with the cuts where . From those cuts, all the corresponding primary occurrences aligned with the boundaries between copies of (i.e., with the same alignment, ) will be captured.
5.1 Case
To capture the primary occurrences with cut inside type-L rules where , we will incorporate the points and into the enhanced grid outlined in Sections 3 and 4, assigning the values and to each, respectively. The point will capture the occurrences where . Note that these occurrences will also find the point , so the final result will be .
The point will also account for the primary occurrences where and . Observation 6 establishes that , so for each such primary occurrence of cut , with offset in , there is a second primary occurrence at with cut , where and . This second cut will not be captured by the points we have inserted because . The other occurrences where matches to the left of fall within (and thus are not primary), because we already have in this second occurrence. Thus, for each of the copies of (save the last), we will have two primary occurrences. This yields a total of occurrences, which are properly counted in the points . See Figure 2.
5.2 Case
We first show that, for to be longer than in some run-length rule, must be periodic.
Lemma 8.
Let , with , have a primary occurrence with cut in the rule , with and . Then it holds that .
Proof.
Since and is contained within , by branch 3 of Definition 1, must be a period of . Thus, . Suppose, for contradiction, that . According to Lemma 2, because is a period of , it follows that divides . Since is contained in , again by branch 3 of Definition 1 it follows that is a period of , and thus of , contradicting the assumption that . Hence, we conclude that .
Note that is then periodic because , and is also periodic by branch 3 of Def. 1, because it occurs inside and .
We distinguish two subcases, depending on whether is longer than or not. If it is, we must ensure that in the alignments we count the occurrence is fully within . If it is not, we must ensure that the alignments we count do correspond to primary occurrences (i.e., they cross a border between copies of ).
5.2.1 Case
To handle this case, we construct a specific data structure based on the period . The proposed solution is supported by the following lemma.
Lemma 9.
Let , with , have a primary occurrence with cut in the type-L rule , with , , and . Then, the number of primary occurrences of in is .
Proof.
Since , can be aligned at the end of the positions where starts in . No other alignments are possible for the cut because, by Lemma 8, and another alignment would imply that aligns with itself with an offset smaller than , a contradiction by branch 2 of Definition 1.
Those alignments correspond to primary occurrences only if does not fall completely within . The alignments that correspond to primary occurrences are then those where is aligned at the end of the last ending positions of copies of , all of which start within because . This is equivalent to , as by Lemma 8. Thus, the number of primary occurrences of in is . See Figure 3.
Based on Lemma 9 we introduce our first period-based data structure. Considering the solution described in Section 4, where Property 1 holds, the challenge with type-L rules (i.e., rules that differ from their transformed version ) is that the number of alignments with cut inside is , but does not determine . We will instead use to index those nonterminals .
For each type-L rule ( being its transformed version), we compute its signature (recall Section 2.3) and store it in a perfect hash table . Each entry in table , which corresponds to a specific signature , will be linked to an array . Each position represents a type-L rule where . The rules are sorted in by decreasing lengths . We also store a field with the cumulative sum
Given a pattern , we first calculate its shortest period . For each cut with , we compute for to identify the corresponding array in . Note that we only consider the cuts where , as this corresponds precisely to for the rules stored in ; note . In addition, the condition ensures that , thus we are correctly enforcing the condition stated in this subsection and focusing, one by one, on the occurrences for which each alignment satisfies . We will find in every (transformed) rule where , sharing the period with , as well as its prefix . Once we have obtained the array , we find the largest such that . The number of primary occurrences for the cut in type-L rules where is then .
5.2.2 Case
Our analysis for the remaining case is grounded on the following lemma.
Lemma 10.
Let , with , have a primary occurrence in a type-L rule with cut , with and . Then it holds that and .
Proof.
If is a type-L rule and has an occurrence within such that , then we have (by Observation 6). Since we can express as , we can similarly use Lemma 8 to conclude that ; further, .
Analogously to Lemma 8, Lemma 10 establishes that, when is sufficiently long, it holds that , so all pertinent rules of the form can be classified according to their minimal period, . This period coincides with when has an occurrence in a type-L rule such that . Further, .
We also need an analogous to Lemma 9 for the case ; this is given next.
Lemma 11.
Let , with , have a primary occurrence with cut in the type-L rule , with , , and . Then, the number of primary occurrences of in is .
Proof.
Since , can be aligned at the end of the positions where starts in . By the same argument of the proof of Lemma 9, no other alignments are possible for the cut . Unlike in Lemma 9, all those alignments correspond to primary occurrences, because is always long enough to exceed . Also unlike in Lemma 9, may exceed , in which case the occurrence must not be counted in this rule. The alignments that must not be counted are then those where is aligned at the end of the last ending positions of copies of . This is equivalent to , as by Lemma 10. Thus, the number of primary occurrences of in is . See Figure 4.
We then enhance table , introduced in Section 5.2.1, with a second period-based data structure. Each entry in table , corresponding to some , will additionally store a grid . In this grid, each row represents a type-L rule whose transformed version is , that is, such that . The rows are sorted by increasing lengths (note for all in ). The columns represent the different exponents of the transformed rules. The row of rule has then a unique point at column , and we associate two values with it: and . Since no rule appears in more than one grid, the total space for all grids is in .111We use the grid representation described in Section 2.4, which assumes that the point coordinates lie in rank space. Our grids can be transformed accordingly without affecting the asymptotic space usage or query time.
Given a pattern , we proceed analogously as explained at the end of Section 5.2.1 in order to identify : We compute , and for each cut with , we calculate , for , to find the corresponding grid in . On the type-L rules , this tries out every possible occurrence for which , one by one, from to . The limit can also be set because, by Lemma 10, it must hold on the rules of we find with the cut .
We must enforce two conditions on the rules of to consider: (a) as corresponds in this subsection, and (b) , that is, fits within . The complying rules then contribute by Lemma 11.
To enforce those conditions, we find in the largest row representing a rule such that . We also find the smallest column where . The set of rules corresponding to points in the range of the grid is then the set of type-L run-length rules where we have a primary occurrence with . We aggregate the values and from the range, which yields the correct sum of all the pertinent occurrences (note the analogy with Eqs. (1) and (2)):
Figure 5 gives a thorough example.
5.3 The final result
Our structure extends the grid of Section 4, built for non-run-length rules, with one point per run-length rule: those of type-E are handled as described in Section 4 and those of type-L as in Section 5. Thus the structure is of size and range queries on the grid take time . Occurrences on such a grid are counted in time [7, Thm. A.5]. This is also the time to count the occurrences in type-E rules for our solution, and those in type-L rules when (Section 5.1).
For our period-based data structures (Sections 5.2.1 and 5.2.2), we calculate in time [11], and compute all prefix signatures of in time as well, so that later any substring signature is computed in time (Section 2.3). The limits in the arrays and in the grids can be binary searched in time . The range sums over and take time . They are repeated for each of the cuts of , adding up to time . Those are then within the previous time complexities as well.
Theorem 12.
Let a RLCFG of size represent a text . Then, for any constant , we can build in expected time an index of size that counts the number of occurrences of a pattern in in time .
Just as for previous schemes [7, Sec. 6.6], the construction time is dominated by the expected time to build the collision-free Karp–Rabin functions [4]. Although the construction is randomized, the algorithm is Las-Vegas type and thus it always produces a correct index; query results are always correct and their time is deterministic worst-case. Other construction costs specific of our index are the time to build Chazelle’s range sums structures [6], and the cost to compute the period of every run-length rule . Those costs sum up to because the top-level run-length rules in the grammar tree add up to length at most , and the top-level descendants of expand at most to . An easy induction shows that the expansions below add up to length at most , so the total expansion length is at most twice that of the top-level run-length rules.
Space-time tradeoffs
The bulk of the query cost owes to the time of the geometric queries. Other space-time tradeoffs are possible. We start with a geometric result of independent interest.
Lemma 13.
For any constant , we can build in time a data structure representing weighted points on an grid, using space , which can sum the weights on any orthohonal range in time . It is also possible to obtain (1) space and time and (2) space and time.
Proof.
Navarro’s solution [44, Thm. 3] represents such a grid with a wavelet tree [22] (assuming there is exactly one point per column, but it is easy to reduce the general case to this one). This structure has levels. The grid points are represented in -coordinate order in the first level, and their order is progressively shuffled until the last level, which represents the points in -coordinate order. The coordinates are not represented explicitly; only one bit is used to represent each point at each level, for a total of bits (which is in space if measured in words). A two-dimensional query is projected onto ranges along different levels, and the query must sum the weights of the points across all those ranges. To save (space and) time, (only) one cumulative sum is precomputed and stored every consecutive weights at every level, so that in total only sums are stored overall, and space is used for those accumulators.
When adding the weights over one range, the sum over most of it is obtained by subtracting two accumulators, and just weights must be explicitly obtained to complete the sum. Those weights are obtained with a structure [6, 38] that takes time and bits (or words) of additional space, for any . Multiplying the ranges to sum, the explicit weights to obtain in each range, and the cost to obtain each weight, we reach the claimed term [44], using constant .
To obtain the desired tradeoff, we will set accumulators every values, which yields space. The time will be then . By choosing a non-constant , the space of the data structure to compute individual weights raises to , and the time becomes .
Tradeoff (1) is obtained by setting , in which case the space of the data structure to compute individual weights dominates. Tradeoff (2) is obtained by setting , in which case we do not need at all that data structure: we have all precomputed prefix sums and answer each range sum in constant time, for a total of time.222Chazelle [6] also obtains tradeoff (1) and explores the other spaces, but his time never goes below because he addresses the more general case of semigroups, with no inverses. Our result is presented for numeric sums, but it can be extended to algebraic groups. All the variants are built in time [6].
By using those grid representations, we obtain tradeoffs in our index.
Corollary 14.
Let a RLCFG of size represent a text . Then, for any constant , we can build in expected time an index of size that counts the occurrences of a pattern in in time . We can also obtain space with time , and space with time .
5.4 An application
Recent work [20, 41] shows how to compute the maximal exact matches (MEMs) of in , which are the maximal substrings of that occur in , in case is represented with an arbitrary RLCFG. Navarro [45] extends the results to -MEMs, which are maximal substrings of that occur at least times in . To obtain good time complexities for large enough , he resorts to counting occurrences of substrings with the grammar. His Thm. 7, however, works only for CFGs, as no efficient counting algorithm existed on RLCFGs. In turn, his Thm. 8 works only for a particular RLCFG. We can now state his result on an arbitrary RLCFG; by his Thm. 11 this also extends to “-rare MEMs”.
Corollary 15 (cf. [45, Thm. 7]).
Let a RLCFG of size generate only . Then, for any constant , we can build a data structure of size that finds the -MEMs of any given pattern , for any given with , in time .
6 Conclusion
We have presented the first solution to the problem of counting the occurrences of a pattern in a text represented by an arbitrary RLCFG, which was posed by Christiansen et al. [7] in 2020 and solved only for particular cases. This required combining solutions to CFGs [44] and particular RLCFGs [7], but also new insights for the general case. The particular existing solutions required that is the shortest period of in rules . While this does not hold in general RLCFGs, we proved that, except in some borderline cases that can be handled separately, the shortest periods of the pattern and of must coincide. While the particular solutions could associate with the period of the pattern, we must associate many strings that share the same shortest period, and require a more sophisticated geometric data structure to collect only those that qualify for our search. Despite those complications, however, we manage to define a data structure of size from a RLCFG of size , that counts the occurrences of in in time for any constant , the same result that existed for the simpler case of CFGs. Our approach extends the applicability of arbitrary RLCFGs to cases where only CFGs could be used, equalizing the available tools to handle both types of grammars.
References
- [1] Djamal Belazzougui, Fabiano C Botelho, and Martin Dietzfelbinger. Hash, displace, and compress. In Proc. European Symposium on Algorithms (ESA), pages 682–693. Springer, 2009. doi:10.1007/978-3-642-04128-0_61.
- [2] P. Bille, M. B. Ettienne, I. L. Gørtz, and H. W. Vildhøj. Time-space trade-offs for Lempel-Ziv compressed indexing. Theoretical Computer Science, 713:66–77, 2018. doi:10.1016/J.TCS.2017.12.021.
- [3] P. Bille, G. M. Landau, R. Raman, K. Sadakane, S. S. Rao, and O. Weimann. Random access to grammar-compressed strings and trees. SIAM Journal on Computing, 44(3):513–539, 2015. doi:10.1137/130936889.
- [4] Philip Bille, Inge Li Gørtz, Benjamin Sach, and Hjalte Wedel Vildhøj. Time–space trade-offs for longest common extensions. Journal of Discrete Algorithms, 25:42–50, 2014. doi:10.1016/J.JDA.2013.06.003.
- [5] M. Charikar, E. Lehman, D. Liu, R. Panigrahy, M. Prabhakaran, A. Sahai, and A. Shelat. The smallest grammar problem. IEEE Transactions on Information Theory, 51(7):2554–2576, 2005. doi:10.1109/TIT.2005.850116.
- [6] B. Chazelle. A functional approach to data structures and its use in multidimensional searching. SIAM Journal on Computing, 17(3):427–462, 1988. doi:10.1137/0217026.
- [7] Anders Roy Christiansen, Mikko Berggren Ettienne, Tomasz Kociumaka, Gonzalo Navarro, and Nicola Prezza. Optimal-time dictionary-compressed indexes. ACM Transactions on Algorithms (TALG), 17(1):1–39, 2020. doi:10.1145/3426473.
- [8] F. Claude and G. Navarro. Self-indexed grammar-based compression. Fundamenta Informaticae, 111(3):313–337, 2010. doi:10.3233/FI-2011-565.
- [9] F. Claude and G. Navarro. Improved grammar-based compressed indexes. In Proc. 19th International Symposium on String Processing and Information Retrieval (SPIRE), pages 180–192, 2012.
- [10] Francisco Claude, Gonzalo Navarro, and Alejandro Pacheco. Grammar-compressed indexes with logarithmic search time. Journal of Computer and System Sciences, 118:53–74, 2021. doi:10.1016/J.JCSS.2020.12.001.
- [11] Maxime Crochemore and Wojciech Rytter. Jewels of stringology: text algorithms. World Scientific, 2002.
- [12] H. Ferrada, T. Gagie, T. Hirvola, and S. J. Puglisi. Hybrid indexes for repetitive datasets. Philosophical Transactions of the Royal Society A, 372(2016):article 20130137, 2014.
- [13] H. Ferrada, D. Kempa, and S. J. Puglisi. Hybrid indexing revisited. In Proc. 20th Workshop on Algorithm Engineering and Experiments (ALENEX), pages 1–8, 2018.
- [14] N. J. Fine and H. S. Wilf. Uniqueness theorems for periodic functions. Proceedings of the American Mathematical Society, 16(1):109–114, 1965.
- [15] M. L. Fredman, J. Komlós, and E. Szemerédi. Storing a sparse table with worst case access time. Journal of the ACM, 31(3):538–544, 1984. doi:10.1145/828.1884.
- [16] T. Gagie, P. Gawrychowski, J. Kärkkäinen, Y. Nekrich, and S. J. Puglisi. A faster grammar-based self-index. In Proc. 6th International Conference on Language and Automata Theory and Applications (LATA), LNCS 7183, pages 240–251, 2012.
- [17] T. Gagie, P Gawrychowski, J. Kärkkäinen, Y. Nekrich, and S. J. Puglisi. LZ77-based self-indexing with faster pattern matching. In Proc. 11th Latin American Symposium on Theoretical Informatics (LATIN), pages 731–742, 2014.
- [18] T. Gagie, G. Navarro, and N. Prezza. Fully-functional suffix trees and optimal text searching in BWT-runs bounded space. Journal of the ACM, 67(1):article 2, 2020.
- [19] Moses Ganardi, Artur Jez, and Markus Lohrey. Balancing straight-line programs. Journal of the ACM, 68(4):27:1–27:40, 2021. doi:10.1145/3457389.
- [20] Y. Gao. Computing matching statistics on repetitive texts. In Proc. 32nd Data Compression Conference (DCC), pages 73–82, 2022.
- [21] Pawel Gawrychowski, Adam Karczmarz, Tomasz Kociumaka, Jakub Lacki, and Piotr Sankowski. Optimal dynamic strings. In Proc. 29th Annual ACM-SIAM Symposium on Discrete Algorithms (SODA), pages 1509–1528, 2018. doi:10.1137/1.9781611975031.99.
- [22] R. Grossi, A. Gupta, and J. S. Vitter. High-order entropy-compressed text indexes. In Proc. 14th Annual ACM-SIAM Symposium on Discrete Algorithms (SODA), pages 841–850, 2003.
- [23] A. Jez. Approximation of grammar-based compression via recompression. Theoretical Computer Science, 592:115–134, 2015. doi:10.1016/J.TCS.2015.05.027.
- [24] A. Jez. A really simple approximation of smallest grammar. Theoretical Computer Science, 616:141–150, 2016. doi:10.1016/J.TCS.2015.12.032.
- [25] Juha Kärkkäinen and Esko Ukkonen. Lempel-Ziv parsing and sublinear-size index structures for string matching. In Proc. 3rd South American Workshop on String Processing (WSP), pages 141–155, 1996.
- [26] R. M. Karp and M. O. Rabin. Efficient randomized pattern-matching algorithms. IBM Journal of Research and Development, 2:249–260, 1987.
- [27] D. Kempa and N. Prezza. At the roots of dictionary compression: String attractors. In Proc. 50th Annual ACM Symposium on the Theory of Computing (STOC), pages 827–840, 2018.
- [28] Dominik Kempa and Tomasz Kociumaka. Collapsing the hierarchy of compressed data structures: Suffix arrays in optimal compressed space. In Proc. 64th IEEE Annual Symposium on Foundations of Computer Science (FOCS), pages 1877–1886, 2023. doi:10.1109/FOCS57990.2023.00114.
- [29] J. C. Kieffer and E.-H. Yang. Grammar-based codes: A new class of universal lossless source codes. IEEE Transactions on Information Theory, 46(3):737–754, 2000. doi:10.1109/18.841160.
- [30] Tomasz Kociumaka, Gonzalo Navarro, and Francisco Olivares. Near-optimal search time in -optimal space, and vice versa. Algorithmica, 86(4):1031–1056, 2024. doi:10.1007/S00453-023-01186-0.
- [31] Tomasz Kociumaka, Gonzalo Navarro, and Nicola Prezza. Toward a definitive compressibility measure for repetitive sequences. IEEE Transactions on Information Theory, 69(4):2074–2092, 2023. doi:10.1109/TIT.2022.3224382.
- [32] Tomasz Kociumaka, Jakub Radoszewski, Wojciech Rytter, and Tomasz Walen. Internal pattern matching queries in a text and applications. In Proc. 26th Annual ACM-SIAM Symposium on Discrete Algorithms (SODA), pages 532–551, 2015. doi:10.1137/1.9781611973730.36.
- [33] S. Kreft and G. Navarro. On compressing and indexing repetitive sequences. Theoretical Computer Science, 483:115–133, 2013. doi:10.1016/J.TCS.2012.02.006.
- [34] J. Larsson and A. Moffat. Off-line dictionary-based compression. Proceedings of the IEEE, 88(11):1722–1732, 2000. doi:10.1109/5.892708.
- [35] A. Lempel and J. Ziv. On the complexity of finite sequences. IEEE Transactions on Information Theory, 22(1):75–81, 1976. doi:10.1109/TIT.1976.1055501.
- [36] S. Maruyama, H. Sakamoto, and M. Takeda. An online algorithm for lightweight grammar-based compression. Algorithms, 5(2):214–235, 2012. doi:10.3390/A5020214.
- [37] G. Navarro. Spaces, trees and colors: The algorithmic landscape of document retrieval on sequences. ACM Computing Surveys, 46(4):article 52, 2014. 47 pages.
- [38] G. Navarro. Wavelet trees for all. Journal of Discrete Algorithms, 25:2–20, 2014. doi:10.1016/J.JDA.2013.07.004.
- [39] G. Navarro. Indexing highly repetitive string collections, part I: Repetitiveness measures. ACM Computing Surveys, 54(2):article 29, 2021.
- [40] G. Navarro. Indexing highly repetitive string collections, part II: Compressed indexes. ACM Computing Surveys, 54(2):article 26, 2021.
- [41] G. Navarro. Computing MEMs on repetitive text collections. In Proc. 34th Annual Symposium on Combinatorial Pattern Matching (CPM), page article 22, 2023.
- [42] G. Navarro, F. Olivares, and C. Urbina. Balancing run-length straight-line programs. In Proc. 29th International Symposium on String Processing and Information Retrieval (SPIRE), pages 117–131, 2022.
- [43] G. Navarro and N. Prezza. Universal compressed text indexing. Theoretical Computer Science, 762:41–50, 2019. doi:10.1016/J.TCS.2018.09.007.
- [44] Gonzalo Navarro. Document listing on repetitive collections with guaranteed performance. Theoretical Computer Science, 772:58–72, 2019. doi:10.1016/J.TCS.2018.11.022.
- [45] Gonzalo Navarro. Computing MEMs and relatives on repetitive text collections. ACM Transactions on Algorithms, 21(1):article 12, 2025.
- [46] C. Nevill-Manning, I. Witten, and D. Maulsby. Compression by induction of hierarchical grammars. In Proc. 4th Data Compression Conference (DCC), pages 244–253, 1994.
- [47] T. Nishimoto, T. I, S. Inenaga, H. Bannai, and M. Takeda. Fully dynamic data structure for LCE queries in compressed space. In Proc. 41st International Symposium on Mathematical Foundations of Computer Science (MFCS), pages 72:1–72:15, 2016.
- [48] Sofya Raskhodnikova, Dana Ron, Ronitt Rubinfeld, and Adam Smith. Sublinear algorithms for approximating string compressibility. Algorithmica, 65:685–709, 2013. doi:10.1007/S00453-012-9618-6.
- [49] W. Rytter. Application of Lempel-Ziv factorization to the approximation of grammar-based compression. Theoretical Computer Science, 302(1-3):211–222, 2003. doi:10.1016/S0304-3975(02)00777-6.
- [50] H. Sakamoto. A fully linear-time approximation algorithm for grammar-based compression. Journal of Discrete Algorithms, 3(2–4):416–430, 2005. doi:10.1016/J.JDA.2004.08.016.
- [51] J. A. Storer and T. G. Szymanski. Data compression via textual substitution. Journal of the ACM, 29(4):928–951, 1982. doi:10.1145/322344.322346.
- [52] K. Tsuruta, D. Köppl, Y. Nakashima, S. Inenaga, H. Bannai, and M. Takeda. Grammar-compressed self-index with Lyndon words. CoRR, 2004.05309, 2020. arXiv:2004.05309.