Manuscript Offprint
arXiv:2610.32298Exact Algorithms and Complexity of the Smallest Grammar Problem
Abstract
The Smallest Grammar Problem (SGP) asks for a smallest straight-line grammar generating a given string, where the size of a grammar is the total length of its right-hand sides. The main difficulty is that rules may be nested: which repeated fragments receive rules affects the value of all other fragments, so locally optimal choices need not combine into a globally optimal grammar.
Our algorithmic results start from a simple structural fact: in an optimal grammar, one can choose an occurrence of the expansion of each auxiliary nonterminal such that the chosen intervals are pairwise disjoint. Thus, although rules are nested, the entire dictionary can be read off from a single partition of the input. This disjoint-representative property decouples the choice of the dictionary, which we enumerate via partitions, from the form of the individual rules, which we compute by dynamic programming. It underlies our algorithmic results and the polynomial formulation; the hardness results rely on a separate encoding-and-projection technique.
First, combining disjoint representatives with a bound on how often dictionary strings of length two are referenced, we obtain an exact algorithm running in time and words of space, where . This improves the bound of Casel et al. for general grammars.
Second, we study the role of the alphabet size. Over a small alphabet there are few short strings, so they can be enumerated by content rather than by position. With the alphabet size and , we give a -time algorithm, which is subexponential for every fixed alphabet. On the other hand, we prove that SGP remains NP-complete over a binary alphabet, answering a question of Casel et al., and we construct hard instance families of tunable alphabet size on which, under ETH, no -time algorithm exists. Both bounds are governed by and differ only by a factor of in the exponent.
Third, disjoint representatives also serve as certificates. For every , they yield a constant-degree integer polynomial formulation of the decision problem with variables and evaluation time. By the barrier theorem of Belova, Golovnev, Kulikov, Mihajlin, and Sharipov, any proof that SGP is -SETH-hard under their deterministic fine-grained reductions, for a constant , would also prove a new lower bound for Boolean series-parallel circuits or for arithmetic circuits.
Keywords. Smallest grammar problem; grammar-based compression; exact algorithms; alphabet encoding; ETH.
1 Introduction
When a string contains many repeated fragments, a straight-line grammar can define each fragment once and refer to it thereafter through a nonterminal. Since rules may refer to other rules, repetitions nested several levels deep can be represented as well. Such grammars are the basic representation in grammar-based compression and also support indexing directly on the compressed text [4]. A smallest grammar for a string T marks the limit of this form of compression and serves as the benchmark for approximation algorithms. Finding it is the Smallest Grammar Problem (SGP); throughout, the size of a grammar is the total number of symbols on the right-hand sides of its rules.
It is precisely the nesting of rules that makes exact algorithms difficult. Two useful fragments may contain one another, their occurrences in the input may overlap, and once a fragment is selected, one must still decide which shorter fragments define it. A direct enumeration of rules must therefore handle two issues at once: which dictionary to use, and how the rules depend on one another. Charikar et al. [1] studied approximation algorithms and the complexity of SGP. Casel et al. [2] showed that the problem remains NP-complete even over fixed alphabets of 24 or 17 symbols, and gave an -time exact algorithm for general grammars, where .
Our starting point is the following observation: although the rules of an optimal grammar may be nested, its dictionary can always be specified by pairwise disjoint intervals of the input. More precisely, for the expansion of each auxiliary nonterminal one can choose an occurrence such that the chosen representative intervals are pairwise disjoint. Taking these intervals as blocks and every remaining position as a block of its own, we can read off the whole dictionary from a partition of the input. Once the dictionary is fixed, a shortest parsing of each rule can be computed by dynamic programming. Hence, enumerating all partitions and computing shortest parsings for each is guaranteed to find an optimal grammar.
This framework admits further savings. For dictionary strings of length two, we additionally exploit how often they are referenced in an optimal grammar, which reduces the enumeration enough to bring the base of the exponent below two. Disjoint representatives also suit the small-alphabet setting: short strings are enumerated by content and long strings by the positions of their disjoint occurrences, and balancing the two yields a time bound that depends on the alphabet size.
How much room for improvement do these algorithms leave? To address this question, we turn to hardness over small alphabets. Here an additional difficulty arises: once the source symbols are encoded, a target grammar may reuse fragments of codewords, so the optimum before encoding does not carry over directly. We overcome this obstacle by quantitatively comparing grammar sizes before and after encoding. This yields NP-completeness of binary SGP as well as ETH lower bounds that depend on the alphabet size. The role of the alphabet is thus visible from both sides: in the amount of enumeration performed by the algorithm, and in the encoding length of hard instances.
Theorem 1.1. SGP can be solved exactly in time and machine words of space, and an optimal grammar can be output within the same asymptotic bounds, where
This improves the bound of [2] for general grammars to . The smaller base 1.8392 in [2] applies only to 1-level grammars, the restricted case in which only the start rule may refer to nonterminals; our algorithm handles fully general nested grammars.
Next we take the alphabet size into account. Let and , and let
It is helpful to view as a number of digits: writing in base takes exactly digits, which differs from by at most one. This interpretation matches the counting in the algorithm: there are strings of length and , and the algorithm compares with to decide which strings to enumerate by content and which by position.
Theorem 1.2.
- For every input of length over at most symbols, SGP can be solved exactly in
time and machine words of space.
- For every polynomial-time computable integer function , there is a polynomial-time reduction from Vertex Cover on graphs of maximum degree at most three to SGP. For a source graph with vertices and at least one edge, the target string satisfies
If ETH holds, then no algorithm solves SGP on this instance family in time
It is no coincidence that both parts of the theorem are governed by . In the upper bound, this quantity arises because long disjoint representatives are few; in the lower bound, it arises because the reduction represents the labels of the source graph by codewords of average length , so that . The construction and the exact optimum of the target string are given in Section 6.
Table 1 compares several alphabet regimes. The algorithmic upper bounds hold for all inputs satisfying the respective alphabet restriction, whereas the ETH lower bounds refer to the corresponding hard instance families; the fixed-alphabet row relies on Corollary 1.3 below.
| Alphabet size | Running time ruled out by ETH | Exact algorithm |
|---|---|---|
| fixed, at least two symbols | ||
| , fixed | ||
| , fixed |
Table 1: Lower and upper bounds for several alphabet regimes.
The table exhibits a clear threshold. Whenever , we have and the algorithm runs in subexponential time; for with , the ETH lower bound for the corresponding family rules out subexponential algorithms. Note, however, that the entries describe growth rates and do not yield statements about every exact alphabet size. For instance, if and all symbols are distinct, then itself already gives an optimal grammar of size .
At the other extreme, the binary case may at first seem counterintuitive: the algorithmic gains from a small alphabet coexist with NP-completeness.
Corollary 1.3. The decision version of SGP over the binary alphabet is NP-complete. Under ETH, it has no -time algorithm.
This answers the question on binary alphabets posed by Casel et al. [2, Section 6.1]: computing a smallest grammar is NP-hard even for inputs over two symbols. Our proof starts from the 24-letter reduction of [2], establishes a constant additive bound between the optima before and after encoding, and then takes a constant number of copies of the source graph to separate the decision threshold from this constant error. Masierak's preprint [7] also reports NP-completeness over a binary alphabet under the standard measure of total right-hand side length, via a different route that starts from the assembly index and then converts between size measures.
Our last result uses disjoint representatives differently. Besides guiding the enumeration, they provide an interval-based certificate for a grammar; translating such certificates into polynomials yields a conditional statement about SETH-hardness proofs themselves.
Corollary 1.4. For every constant , the decision version of SGP has an explicit constant-degree integer polynomial formulation of complexity . Consequently, for every constant , if SGP is -SETH-hard under the deterministic fine-grained reductions defined by Belova, Golovnev, Kulikov, Mihajlin and Sharipov (BGKMS) [5], then at least one of the following holds:
• contains a language that requires Boolean series-parallel circuits of size ;
- for every constant , there is an explicit family of constant-degree integer polynomials that requires arithmetic circuits of size .
Here m denotes the number of inputs of the circuit or the number of variables of the polynomial. Informally, Corollary 1.4 states that proving SETH-hardness of SGP within the BGKMS framework is at least as hard as proving circuit lower bounds that are widely regarded as difficult.
1.2 Techniques
Disjoint representatives arise from a simple pruning of the derivation tree. During a traversal, each auxiliary nonterminal is expanded only at its first encounter, and later encounters become leaves. Since every auxiliary nonterminal of an optimal grammar is referenced at least twice, it has at least one unexpanded leaf. The leaves occupy pairwise disjoint intervals of the input, so choosing one leaf per nonterminal yields the representatives. This pruning is exactly the grammar tree of [4]; Section 3 uses it to enumerate optimal dictionaries. Section 4 goes one step further and selects, among all optimal grammars, one with the fewest rules; in such a grammar every dictionary string of length two is referenced at least three times. This additional condition substantially reduces the number of candidates for short dictionary strings and is what brings the base of the exponent below two.
Section 5.1 splits the dictionary by length and enumerates the two parts differently. Short strings are enumerated by content, and their number is bounded in terms of the alphabet size; long strings are enumerated by the positions of their disjoint representatives, and their number is bounded in terms of the input length. For sufficiently large R, with a length threshold of about , there are short strings and long representatives. The logarithmic overhead of enumerating these representatives accounts for the factor in Theorem 1.2.
On the hardness side, the main technical difficulty is translating an encoded grammar back into a source grammar. Section 5.2 places in each codeword an anchor labeled with the corresponding source symbol and proves a key property: if some occurrence of a fragment contains at least two anchors, then every occurrence of the fragment yields the same sequence of labels. This property allows each target nonterminal to be translated consistently into a rule of the source grammar. For fixed alphabets, the encoding overhead is bounded by a constant, so Section 5.3 needs only a constant number of copies of the source graph to separate this error from the unit gaps caused by the vertex cover size. Growing alphabets are harder because this constant bound is no longer available. Section 6 therefore prepends a carefully designed prefix in which every codeword occurs repeatedly. This forces an optimal grammar to create rules for all codewords, so that the encoding overhead can be computed exactly rather than merely bounded.
Section 7 returns to disjoint representatives but additionally records the references inside the rules, using two layers of input coordinates. Checking a certificate then splits into two parts: equality of substrings and validity of interval positions. Short references are checked in batches and long ones individually. For every fixed , a suitable length threshold ensures that the certificate of an optimal grammar needs only a constant number of variables, while the total number of candidate variables remains . Summing the monomials of all candidate certificates that satisfy the position conditions gives the polynomial formulation required by Corollary 1.4.
2 Preliminaries
2.1 Strings and grammars
Let with . For an interval we write and . Two intervals are disjoint if they share no position. A contiguous substring is also called a factor, and a proper substring is one strictly shorter than the whole string. Throughout, a dictionary entry is a string, whereas an occurrence of it in is an interval; a dictionary entry may have many occurrences, and this distinction will be important.
A straight-line grammar has a set of nonterminals and a start symbol ; every has exactly one rule with . The dependency relation is acyclic, so every nonterminal expands to a unique string . We require and define
We distinguish two lengths: is the number of symbols on a right-hand side, and is the number of characters in the expansion. Nonterminals other than are called auxiliary, and their expansions form the dictionary
hides factors polynomial in . Space is measured in machine words of bits. Symbols of a general alphabet can first be renamed to integers in . Unless stated otherwise, is to base two. For a graph , denotes the size of a minimum vertex cover.
2.2 Reduced grammars and reference counts
We first rule out some obvious redundancies. An optimal grammar has no unreachable rules, since deleting them would reduce its size. No auxiliary rule has a single symbol on its right-hand side: if , writing X at every reference and deleting the rule of A decreases the size by one. Similarly, if , we may take A as the start symbol instead; a start rule with a single symbol is needed only when n = 1.
Less obviously, no two nonterminals of an optimal grammar generate the same string. Such nonterminals would have expansions of equal length, so neither could depend on the other; merging their references and deleting one of the two rules would shrink the grammar without creating a cycle. Accordingly, we call a grammar reduced if it has no unreachable rules and no single-symbol auxiliary rules, and different nonterminals generate different strings; when , we also require that the start rule is not a single nonterminal. In a reduced grammar, every referenced nonterminal has a strictly shorter expansion than the rule in which it occurs; we will use this property frequently.
Let denote the total number of occurrences of A on all right-hand sides. Note that this counts symbol occurrences on right-hand sides, not expansions in the full derivation tree; the two numbers can differ greatly.
Observation 2.1. In an optimal grammar, every auxiliary nonterminal is referenced at least twice.
Proof. If A is referenced only once, replacing this reference by and deleting the rule of A decreases the size by one, contradicting optimality.
Among all grammars of minimum size, we may further choose one with the fewest rules, which we call an optimal grammar with the fewest rules. This refinement may seem inessential, but it gives a stronger lower bound on the number of references to short rules.
Lemma 2.2. In an optimal grammar with the fewest rules, every auxiliary rule with satisfies .
Proof. Expand all references and delete the rule of A. The size changes by
For , this quantity is zero: the size is unchanged, while the number of rules decreases by one, contradicting the choice of the grammar. Together with Observation 2.1, .
In particular, an auxiliary nonterminal whose expansion has length two has two terminals on its right-hand side and is therefore covered by Lemma 2.2.
2.3 Optimal parsing for a fixed dictionary
This subsection treats the easier half of the framework, namely the case of a given dictionary. Let be a set of distinct proper substrings of , each of length at least two. For , let be the minimum number of blocks needed to cut into single characters and shorter dictionary strings. Only dictionary strings with are allowed, so rules built from parsings depend only on shorter strings, which guarantees acyclicity. The total cost of shortest parsings is
For , the following dynamic program computes :
If no dictionary string ends at position j, this reduces to .
The following lemma is central to the framework: shortest parsing never underestimates the optimum, and it attains the optimum for the right dictionary.
Lemma 2.3. For every candidate dictionary , . If is the dictionary of some optimal grammar, then .
Proof. For the inequality, create one nonterminal per dictionary string, define its rule by a shortest parsing, and define the start rule by a shortest parsing of . The resulting grammar generates and has size , so .
For equality, suppose comes from an optimal grammar. Each right-hand side of that grammar is a feasible parsing of the corresponding string, and replacing it by a shortest parsing cannot increase its length, so . Together with the inequality above, this gives equality.
We add two implementation remarks. If the dictionary strings have total length , each can be represented by its endpoints in the input, and the dynamic program can be run rule by rule in words of space. Even if matches are checked character by character, the total running time remains polynomial.
3 Disjoint representatives of optimal grammars
The previous section settled the case of a fixed dictionary, for which optimal parsings can be computed in polynomial time. The remaining problem is the large number of candidate dictionaries. In this section we prove our central structural result: there is a partition of the input whose blocks of length at least two form exactly the dictionary of an optimal grammar. Enumerating candidate dictionaries thus reduces to enumerating partitions of the input.
3.1 Existence of disjoint representatives
Traverse the derivation tree of a reduced grammar depth-first, expanding the rule of each nonterminal at its first encounter and keeping every later encounter of the same nonterminal as a leaf. This is exactly the pruning used for grammar trees in [4]. After pruning, every leaf corresponds to an interval of T.
Lemma 3.1. If every auxiliary nonterminal is referenced at least twice, then in the pruned derivation tree every auxiliary nonterminal A has exactly unexpanded leaves.
Proof. Every reachable rule is expanded exactly once. Hence all expanded right-hand sides together contain occurrences of ; exactly one of them becomes an internal node (the first encounter, which is expanded), and all others become leaves.
The leaves of the pruned tree, read from left to right, spell out T, so their intervals are pairwise disjoint; this is the sole source of disjointness. Writing for the total number of terminals on all right-hand sides and adding up the lengths of the leaves, we obtain
Theorem 3.2. For every reduced grammar satisfying Observation 2.1, one can choose for each dictionary string a representative occurrence in T such that all representative intervals are pairwise disjoint. In particular, there is a partition whose blocks of length at least two, after removing duplicates, are exactly the dictionary of an optimal grammar.
Proof. By Lemma 3.1, every auxiliary nonterminal has at least one unexpanded leaf; here is guaranteed by Observation 2.1. Choosing one leaf per auxiliary nonterminal as its representative gives pairwise disjoint intervals. If every remaining position forms a single-character block, then the blocks of length at least two are exactly the strings of the dictionary.
The following small example illustrates the relation between pruning, leaves, and representatives.
Example 3.1. Consider and the grammar
Its size is , with and . After pruning, the expansions of the leaves are, in order,
The unexpanded leaf of A lies at [4, 6], and the two unexpanded leaves of B lie at [7, 8] and [9, 10]. Taking the first two intervals gives disjoint representatives for the dictionary {abc, bc}. Note that abc and bc have overlapping occurrences in T, which this choice of representatives avoids.
Corollary 3.3. A reduced optimal grammar satisfies
3.2 The partition enumeration algorithm
By Theorem 3.2, some block partition yields exactly the dictionary of an optimal grammar, so the algorithm is straightforward. Deciding independently for each of the gaps between consecutive characters of whether to cut there enumerates all partitions. For each partition, the distinct blocks of length at least two that are proper substrings form a candidate dictionary , and the algorithm returns the minimum of .
Theorem 3.4. This algorithm computes in time and machine words of space, and it can output an optimal grammar within the same asymptotic bounds.
Proof. Correctness follows from two matching bounds: by Lemma 2.3, every candidate has cost at least , and by Theorem 3.2, some partition yields an optimal dictionary, whose cost is exactly .
Each candidate dictionary has total length at most n, so its cost can be computed in polynomial time and linear space, and a depth-first enumeration stores only the current partition. To output an optimal grammar, it suffices to record the endpoints of the best candidate and, after the enumeration, recompute its parsings and trace them back.
4 Enumerating long and short dictionary strings
The bound already improves on , but base two appears to be a natural barrier for partition enumeration. The key to overcoming it is that dictionary strings of length two satisfy a constraint stronger than disjointness: in an optimal grammar with the fewest rules, each of them is referenced at least three times. This suggests treating dictionary strings differently according to their length. Long dictionary strings are enumerated by their occurrence intervals as before, whereas strings of length two are instead selected from the remaining positions by a filter. Requiring at least three occurrences makes this filter restrictive, and the resulting savings bring the base below two.
4.1 Representative occurrences of long strings
Fix an optimal grammar G with the fewest rules and split its dictionary into
Lemma 4.1. There is a set I of pairwise disjoint intervals containing exactly one representative occurrence of each . Let
Then every has at least three complete occurrence intervals inside .
Proof. We modify the pruning of Section 3: nonterminals whose expansion has length at least three are still expanded only at their first encounter, but nonterminals with expansion length two are never expanded and always kept as leaves.
Then every long rule is expanded exactly once. By Observation 2.1, the corresponding non-terminal has at least one unexpanded leaf, and choosing one leaf of each such nonterminal gives I.
Now consider a nonterminal A of expansion length two. Its right-hand side consists of terminals only, so every reference to A lies in the start rule or in a long rule. Each of these rules is expanded exactly once, so all references to A remain as leaves. By Lemma 2.2, . These leaves are pairwise disjoint and disjoint from the chosen long representatives, so they all lie in .
We use Lemma 4.1 as a filter: since the short dictionary strings of an optimal grammar occur at least three times within the remaining positions, restricting to such strings loses no optimal solution. For any set I of long representatives and the corresponding set R of remaining positions, define
Occurrences are counted in the original coordinates of , and characters on either side of a long interval are not considered adjacent; otherwise, spurious “occurrences” spanning a long representative would be counted. With this convention, Lemma 4.1 directly gives .
Observation 4.2.
Proof. Each candidate has at least three valid starting positions, each starting position determines a single string of length two, and there are at most valid starting positions.
This factor of one third acts in the exponent; together with the exclusion of blocks of length two from the partitions, it improves the base from 2 to .
4.2 The algorithm and its correctness
The algorithm is similar to that of Section 3, except that the shape of the partitions is restricted and each partition is followed by an enumeration of subsets of short strings. Specifically, we enumerate block partitions in which every block has length one or at least three; blocks of length two are excluded because short strings are obtained by filtering. For each partition, we perform the following steps.
-
Remove duplicates among the blocks of length at least three to obtain a candidate long dictionary . If one of these blocks is the whole of T, skip the partition.
-
Let be the set of positions of single-character blocks, and compute .
-
For each subset , compute
The algorithm returns the minimum over all candidates. In the degenerate case it uses the single rule .
Lemma 4.3. The algorithm above computes exactly.
Proof. As before, Lemma 2.3 implies that every candidate has value at least .
Conversely, we show that the algorithm encounters an optimal solution. Take the optimal grammar of Lemma 4.1, use its long representatives as blocks, and let every remaining position form a single-character block. This partition has the required shape and is therefore enumerated, with . Since , the subset enumeration reaches . The full candidate dictionary is then exactly , whose cost is .
4.3 Running time and space
The analysis combines the number of partitions and the number of subsets per partition into a single weighted count. If a partition has single-character blocks, then , and by (6) it produces at most candidates for the short dictionary. Assigning weight to each single-character block and weight one to every other block, the total weight bounds the total number of candidates. Let be the total weight of all admissible partitions of length . Then and
By the definition of the weights, the total number of candidates is at most . Let be the solution of
The left-hand side is continuous and strictly decreasing on , tending to infinity as and to zero as , so the solution exists and is unique. Induction on (8) gives
Solving numerically gives .
The space bound is unaffected. A depth-first enumeration stores only the current partition, the long dictionary, and the candidate strings of length two, all within words; since candidate dictionaries have total length , the dynamic program of Lemma 2.3 still runs in linear space. Together with (10), this proves Theorem 1.1; an optimal grammar can be output as in Theorem 3.4.
5 Alphabet size and binary encodings
5.1 An algorithm depending on the alphabet size
Section 4 treated dictionary strings of length two separately. Over a small alphabet, this idea extends to much longer strings: there are only strings shorter than a threshold , and at most disjoint representatives of length at least . We therefore enumerate short strings by content and long strings by position, and choose to balance the two costs.
Suppose the input uses at most symbols, where ; for a unary input we take . Fix an integer threshold . It suffices to consider short strings that occur in as proper substrings, and the number of such candidates shorter than is at most
so all short dictionaries can be enumerated in time. For long strings, we again use Theorem 3.2: the strings of length at least L in an optimal dictionary have disjoint representatives, of which there are at most . It remains to count the families of such disjoint intervals.
Lemma 5.1. The number of families of at most n/L pairwise disjoint nonempty intervals of integer positions in is at most
Proof. For a family of intervals, let be the interval lengths in order and the gap lengths. Substituting to remove the lower bounds gives
By stars and bars, the number of families is . For ,
Summing over all admissible k adds only an term.
The algorithm is now as follows. Enumerate families of intervals, discard intervals shorter than L or covering all of T, and remove duplicate strings to obtain a long dictionary; combine it with every short dictionary and compute the cost by (1). Correctness follows from Lemma 2.3 and Theorem 3.2, and the cost of each candidate dictionary can be computed in polynomial time. Lemma 5.1 therefore gives a total running time of
It remains to choose the threshold. Let . If , take ; then and
Since , we have for sufficiently large . Substituting these bounds into (11) yields
If , we use the algorithm of Section 4; since in this case, the bound (12) holds as well.
The space usage is again linear. When , the long representatives have total length at most n, and for short strings we store each string that occurs in T together with one of its positions, using
space. Hence the algorithm uses machine words, which proves the upper bound of Theorem 1.2. In particular, for a fixed alphabet the running time is , and more generally it is subexponential whenever .
5.2 Binary codewords and anchors
Replace each symbol of the source alphabet by a binary codeword of fixed length, and denote the resulting string by . One direction is easy: a grammar for W becomes a grammar for once a rule is added for each codeword. The converse is harder, since a grammar for may refer to fragments inside codewords, or even to fragments spanning adjacent codewords, and such references correspond to no rule over W. To handle them, we designate in each codeword a position that represents the source symbol.
This position is called an anchor, and its label is the corresponding source symbol. If a reference covers at most one anchor, its labels form the empty string or a single symbol, which poses no problem for the translation. The difficulty lies in references covering several anchors: such a fragment can be represented by a single nonterminal of the source grammar only if all its occurrences yield the same label sequence. The goal of this subsection is to design an encoding that guarantees this consistency.
Let the code length m be a multiple of four, and place the anchor at bit m/2 of each codeword. For adjacent source symbols a, b, define the boundary fragment
We require the encoding to satisfy the following property, which makes boundary fragments unambiguous alignment markers: every occurrence of a boundary fragment uniquely determines the position of a codeword boundary and the labels on both of its sides.
Boundary synchronization (SI). If a window of length in a concatenation of codewords equals , then the window starts at offset inside a codeword and spans the true boundary between and .
Since a boundary fragment lies between any two adjacent anchors, every substring covering two adjacent anchors contains the complete fragment between them.
Lemma 5.2. For every there is a binary fixed-length code satisfying (SI) with code length . Specifically, every multiple of four with and is a valid code length. For , the code length suffices.
Proof. We use the probabilistic method. Choose all mq codeword bits independently and uniformly at random, and fix a boundary fragment and a window
We show that
There are two cases. If , then with . If , equality of the left halves requires the last bits of two different codewords to coincide, which happens with probability exactly ; if , then and the same computation applies to the right halves.
If , the window is misaligned. Consider the graph whose vertices are the random bits involved in the comparison and whose edges are the bitwise equality constraints. Since the phases differ, there are no self-loops, and since each bit occurs at most once in a single window, the graph has maximum degree at most two; hence each connected component is a path or a cycle. A path with edges yields independent constraints, and a cycle with edges yields . Hence the edges provide at least independent constraints, and (14) holds as well.
There are fewer than bad pairs of a boundary fragment and a window, so the union bound gives
For we have , so suffices to make the right-hand side of (15) less than one, which proves existence with . For the concrete case and , direct computation gives
For a fixed alphabet, a suitable code table can thus be hard-wired into the reduction, making it deterministic; Appendix B gives an explicit table for and , together with a verification program.
Now fix a code satisfying (SI) and let
The -th anchor is at position and has label . For an interval of the target string, let be the string of labels of the anchors in , read in order. For adjacent intervals,
The boundary fragment between adjacent anchors and occupies the interval
whose endpoints both lie strictly between the two anchors. The following lemma, which is the key result of this subsection, establishes the consistency discussed above.
Lemma 5.3. Let a factor X occur in at interval I. If I contains at least two anchors, then every other occurrence of X satisfies . Moreover, the anchors have the same relative positions and labels in both occurrences.
Proof. Let the anchors in be with . The boundary fragment between the first two anchors lies entirely in . Since , the same boundary fragment appears at the corresponding offset in .
By (SI), this window in also spans a true codeword boundary at the same phase, with labels and on its two sides. Since all codewords have the same length, all boundaries and anchors of the two occurrences are aligned. Applying (SI) to each pair of adjacent anchors in turn determines all labels, so .
Lemma 5.4. For every binary grammar H generating , there is a grammar over the source alphabet generating W with
Proof. If , a single terminal rule suffices. Assume and delete the unreachable rules of .
We divide the nonterminals into two classes. A nonterminal A is multi-anchor if some occurrence of it contains at least two anchors; by Lemma 5.3, all its occurrences have the same projection, which we denote by . All other nonterminals are local: each of their occurrences has a projection of length at most one, but different occurrences may have different projections, so local nonterminals cannot be translated consistently and are deleted instead. The start symbol S is multi-anchor, with .
For each multi-anchor nonterminal A, we create a nonterminal as follows. Pick any occurrence of A. If the rule is , the right-hand side divides this occurrence into adjacent intervals . We build the new right-hand side symbol by symbol:
• if is a multi-anchor nonterminal, write ;
- if is a local nonterminal or a terminal, write , which is a single source symbol or empty.
Let be the resulting right-hand side and define . By induction along the dependencies of the original grammar, multi-anchor children generate and the other symbols generate directly. By the additivity (16),
All new dependencies are inherited from the original grammar, so the new grammar is acyclic, and its start symbol generates W. Each symbol on a right-hand side is replaced by at most one symbol, so , and the rules of local nonterminals are deleted. Hence .
The proof uses only one property of the encoding: if some occurrence of a fragment contains at least two anchors, then all occurrences of that fragment yield the same labels. Isolating this property gives the form needed in Section 6, which in addition quantifies the savings from deleting local rules.
Projection Theorem. Designate some labeled anchors in a target string X, and let W be the string of their labels read in order, with . Suppose every factor satisfies the following: if one occurrence I of it contains at least two anchors, then every other occurrence satisfies . Then for every straight-line grammar H generating X there is a grammar generating W with
If is the set of local nonterminals, each of whose occurrences contains at most one anchor, then moreover
Proof. Apply the construction of Lemma 5.4. Uniqueness of projections makes the translation of multi-anchor nonterminals consistent, and since local rules are deleted, their right-hand side lengths can be subtracted from the size of the original grammar, which gives (20).
Theorem 5.5. Let be a fixed alphabet with , and use the synchronizing code of Lemma 5.2 with code length . For every nonempty source string ,
In particular, for we may take , and the additive error is at most 3072.
Proof. The left inequality follows by applying Lemma 5.4 to an optimal target grammar. For the right inequality, start from an optimal grammar for , add a rule for every source symbol used, and replace by on the existing right-hand sides. The old rules keep their lengths, the new rules have total length at most , and the resulting grammar generates .
For the fixed-alphabet reduction, a constant additive error suffices: taking a constant number of copies of the source graph makes the decision gap exceed it.
5.3 NP-completeness over a binary alphabet
We now combine Theorem 5.5 with the 24-letter reduction of Casel et al. [2, Section 3], which maps a graph G of maximum degree at most three to a string . If G has N vertices and M edges, then [2, Lemma 8] gives
The size measure of [2] counts the axiom string together with the auxiliary rules; viewing the axiom as the right-hand side of the start rule leaves the size unchanged, so the result applies directly. The output has length ; see Appendix A.2.
One obstacle remains: the vertex cover term in (22) has coefficient one, whereas the additive error of Theorem 5.5 is , which would obscure the decision threshold. We therefore first take copies of the source graph, which amplifies the unit gap in the vertex cover size by a factor of K, so that it exceeds the error. Using the 24-letter code of Theorem 5.5, let
Given a Vertex Cover instance , let be the disjoint union of copies of . Its maximum degree is still at most three, and
Apply the reduction above to and then the binary encoding, obtaining . Denote the part of (22) other than the vertex cover term by
By (22) and Theorem 5.5,
Let . If , the right-hand inequality directly gives . Conversely, if , integrality gives , and so
Since , the two cases are separated. In summary,
Theorem 5.6. The decision version of SGP over a binary alphabet is NP-complete.
Proof. For NP-hardness, note that K and the code length are constants, so can be constructed in polynomial time, and (24) shows that this is a reduction from Vertex Cover on graphs of maximum degree at most three to binary SGP.
Membership in NP requires some care, since the expansions of a grammar can be exponentially long. We may assume that , since otherwise the single rule suffices. A grammar of size at most has at most nonterminals and can be encoded in bits. The verifier checks the format of the rules and the acyclicity of the dependencies, and then computes all expansion lengths in topological order; after deleting unreachable rules, it rejects as soon as some expansion length exceeds . Otherwise, all expansions have length at most , so they can be computed explicitly in polynomial time, and the expansion of the start symbol is compared with the input.
Since the number of copies and the code length are constants, . Combined with the Vertex Cover lower bound of Appendix A.2, this yields the following corollary.
Corollary 5.7. If ETH holds, SGP over a binary alphabet has no -time algorithm. The same lower bound holds for every fixed non-unary alphabet.
For fixed alphabets, the upper bound of Section 5.1 and the lower bound thus differ only by a factor of in the exponent. In particular, NP-completeness and a subexponential exact algorithm coexist.
6 Alphabet size and ETH lower bounds
The upper bound of Section 5.1 varies continuously with the alphabet size. To assess its tightness, we need hard instances with a tunable alphabet size; this section constructs such a family.
We first explain why the strategy of Section 5.3 fails here. There, copies of the source graph amplified the unit gap in the vertex cover size, which worked because the cost of the code table was constant. If grows with the input, so does the error bound ; the required number of copies is then no longer constant, and the resulting increase in the length of the reduction precludes the desired lower bound.
We therefore take a different approach: instead of dominating the error, we compute it exactly. To this end, we prepend to the source string a prefix in which every codeword occurs exactly seven times, which forces an optimal grammar to create a rule for every codeword. The argument has three steps. We first determine all fragments of the source string that can repeat, then determine which repetitions may cross codeword boundaries after encoding, and finally prove that an optimal grammar defines all codewords. The cost of the code table can then be subtracted exactly, rather than merely bounded, when translating back to the source grammar.
6.1 Overview of the reduction
Let be a simple graph with a nonempty edge set and maximum degree at most three, with vertices and edges. Fix an integer . We construct with
whose optimal grammar size is
The constants hidden in the length bound do not depend on . Crucially, (26) is an equality: since can be computed directly, can be read off from .
6.2 The cost of codeword rules
We first bound the cost that an optimal grammar must pay for defining these codewords. The answer is three symbols per codeword, even if the grammar uses rules with two symbols. Suppose a reduced grammar contains r distinct auxiliary nonterminals with
where does not contain . We call these strings complete codewords.
Lemma 6.1. The rules of the complete codewords, together with certain other auxiliary rules whose expansions contain exactly one , have total right-hand side length at least 3r.
Proof. Suppose t of the complete-codeword rules have right-hand sides of length two, and the remaining r - t have length at least three. We show that each of these t rules corresponds to an additional auxiliary rule whose length offsets the saving.
For a two-symbol rule , exactly one of the two children has an expansion containing . This expansion contains the complete half-codeword on one side of the star and a strictly shorter piece on the other side; hence it is neither a single terminal (so the child is an auxiliary nonterminal) nor a complete codeword. Associate with this child.
This association is injective: from the longer side of the star in the child's expansion one recovers (reversing it if necessary), and the position of the longer side is determined by the expansion itself, so no child is associated with two different complete codewords. We thus obtain at least t additional auxiliary rules, each of length at least two. The total cost is at least
Hence, an optimal grammar that defines these complete codewords pays at least 3r for their rules, regardless of how the rules are arranged. In the lower bound proof below, this cost is subtracted from the size of the target grammar.
6.3 Construction of the codewords
The target alphabet consists of three pairwise disjoint groups of symbols:
• vertex digits and separator digits ;
• vertex labels and separator labels ;
• special symbols , , , , , , .
This gives symbols in total, which is the value of in (25); the parameter b controls the alphabet size.
Codewords use the bijective base-b representation with the least significant digit first, in which every positive integer i is written uniquely as
Let and . For define the inner codewords
and for define
Each class has codewords, for a total of .
The codewords are nested, so each can be defined by a short rule: removing the outermost pair of digits from an inner codeword leaves an inner codeword of smaller index or a single , and removing the outer labels from a labeled codeword leaves the corresponding inner codeword. Hence every codeword can be defined by a rule with a right-hand side of length three, and all dependencies point to shorter strings. The total length of all codeword rules is
Although the codeword lengths depend on b, every rule has exactly three symbols on its right-hand side, so (28) is independent of b. This is why (26) does not depend on b.
Next, we fix the order in which codewords occur. The codewords of each class are arranged cyclically in the order
and likewise for the class D: for each index i, the eight codewords with distinct outer labels are listed first, followed by the inner codeword. With this order, any seven consecutive codewords in the cyclic list have pairwise distinct first symbols and, since codewords are palindromes, pairwise distinct last symbols. Section 6.5 uses this property to rule out repetitions across codewords.
6.4 Construction of the source string
Two coloring steps prepare the construction of the source string. Both serve to distinguish adjacent positions by their labels, which restricts repeated factors to a few specific forms.
The first coloring distinguishes the neighbors of each vertex. Join two distinct vertices by an edge whenever they have a common neighbor; the resulting graph has maximum degree at most six and can be colored greedily with seven colors. Denote the color of vertex by . Then distinct neighbors of a vertex in the original graph receive distinct colors.
The second coloring distinguishes the junctions in the edge gadget. Order the edges of the original graph arbitrarily, and orient them one by one as so that ; since every edge has two distinct endpoints, such an orientation always exists. Build the bridge multigraph with edges . Each edge of the original graph contributes at most one bridge incidence to each of its two endpoints, so this graph has maximum degree at most three, and the orientation rules out self-loops. A greedy coloring therefore uses at most five colors; denote the color of the -th bridge edge by . Labels 6, 7, 8 are reserved for the vertex gadgets.
Introduce source symbols , for the codewords , , and keep the symbols , , , , , . Order the source symbols of the two classes according to (29) as
Let and abbreviate . The source string begins with the prefix
The prefix is designed with two goals. The source symbol of every codeword occurs exactly seven times in P, which is often enough to force an optimal grammar to create a rule for it; and because of the seven different cyclic shifts, these seven occurrences have pairwise different neighboring codewords, so no fragment spanning several codewords can be reused. Section 6.6 relies on both properties.
The remainder of the source string encodes the graph. Every vertex occurs once in each of the following five gadgets:
together with the edge gadget
The source string is
Since , all indices lie within the range of the code table. The prefix has length 14Q, the five vertex gadgets have total length 20N, and the edge gadget has length 6M - 1; adding the six separators gives
Define and , and leave all special symbols unchanged. The final instance is
Note that does not depend on : changing affects only the alphabet and the codeword lengths of the target string, whereas the source string and its optimum remain unchanged. We can therefore compute once and treat the influence of separately.
6.5 Repeated factors and the optimum of the source string
Owing to the colorings and the ordering, the repeated factors of the source string can be listed explicitly.
Lemma 6.2. Every factor of of length at least two that occurs more than once has one of the following three forms:
#w_{i}#.
(35)
Proof. We first consider factors of length two, that is, pairs of adjacent source symbols. In the prefix , apart from the position adjacent to, adjacent pairs alternate between the forms and , with indices taken modulo . For fixed , the seven values of give seven different vertex symbols. Hence no adjacent pair of the prefix repeats. In the suffix, two codeword symbols are always separated by , , or , so adjacent pairs of the prefix do not reappear in the suffix either.
In the suffix, each occurs only once. The symbols occur in and : their left neighbors are and , and their right neighbors lie in and in , respectively. The symbols occur in and : their left neighbors are and , and their right neighbors lie in and in , respectively. So no adjacent pair on either side of these symbols repeats. The symbol occurs only once, in , and each in the edge gadget is determined by the index . The vertex symbols next to , are distinguished by the index . The only adjacent pairs that can repeat are therefore and .
Next, consider longer factors. Every adjacent pair in a repeated factor of length at least three must itself repeat, so the factor is built from the two kinds of pairs above; that is, it contains or . The latter form occurs only in the edge gadget, and since every edge is written only once, the same ordered pair does not repeat.
Finally, we show that no extension of repeats. In , its left neighbor is or and its right neighbor is . In the edge gadget, if , its left neighbor is or and its right neighbor is ; if , its left neighbor is and its right neighbor is or the end of the string. Separators of different edges are distinguished by their indices, and different edges incident to have different other endpoints. Hence no extension on either side repeats, and no factor of length at least four repeats either.
By Lemma 6.2, every auxiliary expansion of an optimal grammar has one of the three forms in (35), so can be computed directly. We first add all rules of length two:
Adding these rules does not increase the optimum: defining costs two symbols, and and each contain an occurrence of that can be replaced by , saving exactly two symbols; the same holds for in and . The only other potentially useful rules are , with expansion . Let be the set of vertices for which is used; as we will see, plays the role of a vertex cover.
We now compute shortest parsings gadget by gadget. The prefix contains no repeated factors and must be written with 14Q symbols. Defining all , costs 4N symbols, and defining the another . In through each vertex needs three symbols; in a vertex in needs two and any other vertex three.
The dependence on arises in the edge gadget. The fragment of the edge is . If at least one endpoint lies in , it can be written with two symbols, using one A rule and one L or R rule; if neither endpoint lies in C, three symbols are needed. In addition, each edge except the last requires one symbol . Since Lemma 6.2 lists all repeated factors, the local costs are independent and can be added. Including the six symbols \_j$, the total cost is
It remains to minimize the last two terms, , whose minimum is exactly : for every , adding one endpoint of each uncovered edge yields a vertex cover of size at most this sum, and taking to be a minimum vertex cover makes the second term vanish. Therefore
This completes the analysis of the source string. We now designate anchors in the target string : the central of every codeword carries the label of the corresponding source symbol, and every unencoded special symbol serves as its own anchor and label. Reading these labels in order recovers exactly .
To apply the Projection Theorem, we must also analyze the repeated factors of the target string.
Lemma 6.3. Every repeated factor of that contains is contained in a single codeword or in a single . In particular, it cannot span two codeword centers.
Proof. The proof has three steps: we show that alignments across codeword boundaries are rigid, exclude factors with two centers, and bound how far a factor with one center can extend.
First, we show that a fragment containing is aligned in the same way in any two of its occurrences. The symbol sets are disjoint: apart from the central , vertex codewords use only vertex digits and vertex labels, and separator codewords use only separator digits and separator labels, and these two groups are disjoint. Every codeword has the form , and determines it uniquely.
Suppose a fragment crosses the right boundary of a codeword. Then after the it contains the complete and also the first symbol outside the codeword. In the prefix, this outside symbol belongs to the other class of codewords; in the suffix, it is , , , or . In both cases it cannot coincide with a symbol inside the codeword. Hence, in any other occurrence the codeword must have the same length, since otherwise some position would match an outside symbol with an inside symbol. Equal right halves in turn determine the whole codeword. The left boundary is handled symmetrically. Thus, whenever a repeated fragment crosses a codeword boundary, both occurrences cross the same side of the same codeword.
Second, we exclude factors with two centers. If a repeated factor contains two occurrences of , take two adjacent ones. The fragment from the first center to the second crosses the right boundary of the first codeword and the left boundary of the second; by the first step, both codewords and all special symbols between them are uniquely determined. Hence the corresponding factor of the source string also repeats and contains two encoded source symbols, contradicting Lemma 6.2. So a repeated factor contains at most one .
Third, we bound how far a fragment with one center can extend. In what follows, the prefix and the gadgets refer to their encoded versions. The same codeword occurs seven times in the prefix, and (29) ensures that in every occurrence the first and last symbols of the neighboring codewords differ. Moreover, the neighbors of a codeword in the suffix are special symbols, while in the prefix they belong to the other class of codewords. Consequently, a repeated fragment in the prefix can neither cross a codeword boundary nor have a boundary-crossing occurrence in the suffix.
In the suffix, the separator codewords occur in and with left neighbors and #, and right neighbors in \{\#, \2}{\mathsf{c}{2}}D_{i}^{7}B_{2}B_{3}\mathsf{c}{2}and #, and right neighbors in{#, $3}{\mathsf{c}{1}}D{i}^{8}D_{j}^{c_{e}(j)}$ occur only once in the suffix. Hence a repeated factor containing the center of a separator codeword cannot cross a codeword boundary.
Write for the codeword of the source symbol . The suffix of the target string uses only these vertex codewords. In and its right neighbor is and , respectively; in and its left neighbor is and , respectively, or a gadget separator occurring only once. The only other outside symbol that repeats is #. Table 2 lists the first symbol seen beyond this #; when the end of the string or a gadget separator is reached, the occurrence itself is unique.
| Occurrence | Left of | Right of |
|---|---|---|
| — | ||
| edge gadget, | ||
| edge gadget, |
Table 2: The first symbol beyond the # adjacent to .
The edge colors in the table occur only if the corresponding bridge edge exists. For fixed , different neighbors have different colors , different bridge edges incident to have different colors , and the vertex labels and separator labels come from different groups of symbols. Hence the symbols to be compared on the same side of the table never coincide. Therefore, a repeated fragment can extend beyond by at most the adjacent #, since one step further the symbols differ. This proves the lemma.
Corollary 6.4. If some occurrence of a factor of contains at least two anchors, then all its occurrences have the same projection onto source labels.
Proof. We distinguish cases according to the number of codeword centers in the factor. A factor containing two centers cannot repeat by Lemma 6.3. A repeated factor containing exactly one center lies within a single codeword or within a single ; the proof of Lemma 6.3 also shows that codewords and boundaries have the same relative positions in all occurrences, so the labels of all anchors agree.
It remains to consider factors containing no codeword center but at least two anchors. These anchors can only be unencoded special symbols. If a codeword lies between two special symbols, its central also falls into the factor, which is the previous case; if no codeword lies between them, the consecutive special symbols contain some occurring only once, so the factor does not repeat.
Thus, all conditions of the Projection Theorem are satisfied. When a target grammar is translated back to , the translation is consistent and, by (20), we may subtract the rule lengths of all auxiliary nonterminals each of whose occurrences covers at most one anchor; codeword rules are of this kind.
6.6 Codeword rules in optimal grammars
Lemma 6.5. Every reduced optimal grammar for contains auxiliary nonterminals for all 2Q complete codewords.
Proof. We argue by contradiction, charging the cost to the prefix. Take a reduced optimal grammar and suppose that s > 0 complete codewords are missing.
The symbol occurs only once in , so an auxiliary rule containing cannot be referenced twice, and must be written directly by the start rule. Hence the symbols of the start rule before generate exactly .
This prefix contains 14Q codeword centers. By Lemma 6.3, each right-hand side symbol in the prefix that contains a center generates at most one center: if it generated two, its expansion would have to repeat, which Lemma 6.3 excludes. Hence the prefix needs at least 14Q right-hand side symbols containing centers.
We now show that missing codewords incur an extra cost. For each missing codeword, none of its seven designated occurrences in the prefix can be generated by exactly one right-hand side symbol, since that symbol would be an auxiliary nonterminal expanding to this complete codeword, contradicting that it is missing. Symbols containing a center cannot cross codeword boundaries of the prefix, so at least part of each designated occurrence must be generated by symbols containing no center. A symbol containing no center touches at most two adjacent designated codeword occurrences, since otherwise it would cover the center of the codeword in between. Hence, besides the 14Q symbols above, at least symbols without a center are needed. In total, the start rule uses at least
symbols on .
We now use an exchange argument and add rules for all missing codewords following the construction of Section 6.3. Every new rule has a right-hand side of length three and depends only on shorter codewords, and no existing rule depends on a new nonterminal, so no cycle is created. After this, the part of the start rule covering can be rewritten using complete-codeword nonterminals with exactly 14Q references; all rules outside the prefix and the rest of the start rule remain unchanged. The net change of the grammar size is at most
which is negative since (this is why the prefix contains seven occurrences of each codeword), contradicting optimality. Hence .
We can now combine these results. Let be a reduced optimal grammar for . By Lemma 6.5, it contains complete-codeword rules; by Lemma 6.1, these rules together with the related single-center auxiliary rules cost at least . The expansion of each of these rules contains exactly one and no other anchor, so each occurrence covers at most one anchor, and their lengths may be subtracted in (20). Corollary 6.4 and (20) give
Conversely, take an optimal grammar for , replace every encoded source symbol by the corresponding codeword nonterminal, and add all codeword rules of Section 6.3, of total length exactly 6Q. The old rules keep their lengths, so
The two bounds coincide. In contrast to Section 5.3, the encoding cost is thus computed exactly rather than bounded by a constant. Therefore
Substituting (36) yields (26).
6.7 Size of the reduction and the ETH lower bound
Finally, we bound the size of the reduction and derive the ETH lower bound. Let be the length of the bijective base-b representation of . Inner codewords have length , labeled codewords , and the nine codewords of the same index have total length . The prefix contains every codeword of both classes seven times, so
Uniformly for all admissible b,
The suffix contains codewords, each of length , hence
Since , all digits, outer labels, and special symbols actually occur in the string, so the alphabet size is exactly .
Let . By (38) and ,
Consequently,
where we used . By (39), for every choice of . Moreover, by (26), can be read off directly from . Hence a -time algorithm for SGP would solve Vertex Cover on graphs of maximum degree at most three in time, contradicting the ETH lower bound of Appendix A.2.
Choosing as a constant, as , as , or as a fixed positive power of gives the corresponding rows of Table 1; for smaller fixed alphabets, we use the binary reduction of Section 5.3 instead.
7 Polynomial formulations
In the previous sections, disjoint representatives served as the basis for enumeration. In this section, we use them as certificates. Besides the dictionary, we also record the references inside the rules: the dictionary is specified by disjoint intervals of the input, and the references by intervals with a layer index. The whole grammar is thereby described by coordinates alone. Consequently, for each fixed input length n, such certificates can be encoded by a low-degree polynomial that depends only on n, while the input string T and the threshold k affect only the values of the variables. This is exactly the form required by the BGKMS barrier theorem.
7.1 Requirements of polynomial formulations
We use the non-parameterized polynomial formulation theorem of BGKMS [5, Definitions 2.7 and 2.8 and Theorem 4.3; numbering as in arXiv v5]. For every constant , we need a family of integer polynomials and an evaluation algorithm such that the number of variables and the evaluation time are , the degree is a constant depending only on , the coefficients can be listed explicitly in time polynomial in the number of variables, and
The formulation theorem also requires a bound on the magnitude of the values. To this end, all variables below take values in , all coefficients are nonnegative integers, and we pad the set of variables at the end to meet the magnitude bound.
We adopt two conventions. The input size is the number of characters (after renaming a general alphabet, the bit length is , and the resulting polynomial factors are absorbed by the slack in the exponent of ); and the threshold may be restricted to , since for the single rule suffices.
The -SETH-hardness of BGKMS allows deterministic adaptive oracle queries. Its definition requires a function , independent of the clause width, such that every -SAT instance can be solved in time using an SGP oracle, with query lengths satisfying
7.2 Interval representation of grammars
By Theorem 3.2, we can choose a disjoint representative for every dictionary string of an optimal grammar; let D be the set of these intervals. In this section, D consists of intervals rather than strings: when enumerating candidates, different representative intervals may have the same content, since the polynomial depends only on coordinates.
We use two layers of coordinates. Layer zero is the whole of and corresponds to the start rule; layer one consists of the representative intervals in and corresponds to the auxiliary rules. If each nonterminal reference on a right-hand side is placed on the corresponding interval of that rule's expansion, then a reference is fully described by a pair: a source interval carrying a layer index, and a target representative with . Positions not covered by references are filled with terminals.
Let R be the set of all source intervals. Source intervals within the same layer are pairwise disjoint, and
In addition, a source interval of layer one must be contained in some representative with , and a source interval of layer zero must satisfy . These length conditions make the rule dependencies acyclic, so no separate cycle check is needed; this is important because a certificate contains only coordinates.
The total right-hand side length of the grammar described by the certificate is
Here, the first two terms are the cost of writing all rules with terminals only, and each nonterminal reference replaces a fragment of length by a single symbol, saving symbols.
Example 7.1. For the grammar of Example 3.1, choose and . Layer zero has the four source intervals , , , , corresponding to in the start rule. Layer one additionally has inside , corresponding to in the rule . By (42),
which equals the total right-hand side length of the grammar.
7.3 Variables and the size of certificates
The variables must satisfy two conditions: each certificate uses only a constant number of variables, so that the degree is constant, and the total number of candidate variables is . To this end, we divide references into two classes by length. Short references are grouped by total length, and each group is checked by a single variable; long references are checked individually.
Fix a constant and let . We assume that ; the finitely many remaining small values of are handled separately. Short references are grouped into batches by total length, each batch checked by one variable; long references are checked one at a time. This meets both requirements: the exponent of the total number of variables decreases with , whereas the number of variables used by a single certificate depends only on , not on .
For each pair of interval families we introduce a short-reference variable , where
-
B is a nonempty family of disjoint representatives, each of length in , of total length at most L;
-
R is a family of source intervals in the two-layer coordinates, disjoint within each layer, each of length in , of total length at most ; is allowed.
Its value is
Brackets denote the 0/1 indicator of a proposition. Note that this variable only checks that some representative with matching content exists, without specifying which one; the target representative is chosen when the grammar is reconstructed. This is what allows short references to be checked in groups.
For a source interval and a target representative with , where is a proper-substring interval, we introduce a long-reference variable
where I carries a layer index. There are such variables.
Finally, for we introduce threshold variables
Thus, k affects only the values of the variables , and the polynomial itself does not depend on k, as required by the formulation theorem.
We first bound the total number of variables.
Lemma 7.1. The number of families of disjoint nonempty intervals of integer positions in of total length at most L is at most
Proof. Choose the covered positions, and then mark for each pair of consecutive covered positions whether an interval boundary lies between them; there are at most choices of boundaries. This overcounts, but every valid family is counted, which suffices for an upper bound.
We place the two layers of coordinates consecutively on a line of length 2n and forbid intervals that cross the boundary between the layers. By Lemma 7.1, the number of short-reference variables is at most
Let . Since , standard binomial estimates bound the total number of variables by
Crucially, as , so choosing small enough makes the exponent smaller than any given .
The variables can also be evaluated efficiently. Each short-reference variable can be computed from (43) by comparing source and target intervals, in time; (44) and (45) are also polynomial-time. Hence all variables can be evaluated in
time. The choice of interval boundaries is already accounted for in (46).
It remains to show that a single certificate uses only of these variables.
We use a simple bin packing bound. If items of size at most L and total size W are placed one by one into bins of capacity L, and a new bin is opened only when the current item does not fit, then any two consecutive bins have total load greater than L, so at most bins are used.
Lemma 7.2. A certificate of an optimal grammar satisfying (41) can be represented by short-reference and long-reference variables.
Proof. We pack twice. First, we pack all short representatives by length, obtaining with
Second, for each , we collect all source intervals pointing to representatives in and pack them into groups of total length at most , obtaining ; each bin is represented by one variable . If no source interval points to , its representatives are kept by the variable .
Let be the total length of source intervals pointing to . By (41), , so the number of short-reference variables is at most
Long references are simpler: there are at most long source intervals, each of which is assigned one variable ; since every long representative is referenced at least once, all long representatives are recorded by these variables. The two kinds of variables number at most in total.
7.4 The polynomial and its correctness
We now define the polynomial. Let . For we have , so the number of variables needed in Lemma 7.2 is less than .
Enumerate local variable sequences of length at most , where each entry is an - or a -variable. Let be the set of all target representatives in the sequence, deduplicated by coordinates, and let be the list of occurrences of all source intervals. We call admissible if:
-
distinct intervals in are pairwise disjoint and have lengths in ;
-
source intervals, counted by occurrence, are pairwise disjoint within each layer, and no source interval is listed twice;
-
every layer-one source interval is contained in some with , and every layer-zero source interval satisfies .
Admissibility depends only on coordinates, not on T, so it can be checked when the polynomial is constructed. The same target representative may occur in several variables; it is counted only once when computing . For admissible Q, compute the integer from (42) and define
The empty sequence gives the monomial , representing the trivial grammar that writes directly. The coordinate conditions ensure that , so the index is valid.
The degree of the polynomial is at most , a constant depending only on and hence only on . Enumerating variable sequences and checking the coordinate conditions lists all coefficients in time; when different sequences produce the same monomial, their coefficients add up, so all coefficients are nonnegative integers. Nonnegativity is used in the proof of the converse direction below.
We now relate the values of the polynomial to the optimal grammar size.
Lemma 7.3. For every input ,
Proof. Suppose first that . We take a reduced optimal grammar together with its disjoint representatives. By Lemma 7.2, its certificate can be represented by at most local variables. These variables satisfy all coordinate conditions, all evaluate to one, and , so the corresponding monomial evaluates to one and the polynomial is positive.
Conversely, suppose that the polynomial is positive. Since all coefficients are nonnegative, some monomial has all factors equal to one, and we reconstruct a grammar from it. Create one nonterminal for each of its target representatives J. For each layer-one source interval I inside J, the truth of the local variables allows us to choose a target representative with matching content; write the corresponding reference into the rule and fill the remaining positions with terminals. Layer zero is handled in the same way and gives the start rule.
The reconstructed grammar is valid: every reference points to a strictly shorter expansion, so the dependencies are acyclic, and induction on length shows that every rule generates its representative substring and the start rule generates T. Finally, (42) and the threshold variables ensure that the total size is at most k.
It remains to choose the parameters to meet the requirements of the formulation theorem. Given , first choose a rational with , and then a rational with ; the polynomial factors in (48) and (49) are absorbed by the remaining slack in the exponent. For sufficiently large , add unused variables to pad the number of variables to
The function is strictly increasing, efficiently computable, , and dominates both the original number of variables and the evaluation time. The number of variable sequences in (52) is at most , so for sufficiently large every 0/1 evaluation satisfies
All coefficients can be listed in time, where depends only on and can be chosen as a constant dominating both the degree and the exponent of the construction time. Finally, re-index the polynomial family by the strictly increasing , define the polynomials at unused sizes to be zero, and encode the finitely many small sizes separately. Thus SGP has the required explicit polynomial formulation for every , and applying Theorem 4.3 of BGKMS yields Corollary 1.4.
8 Discussion
The main open question is whether the logarithmic factor in the exponent of our algorithm can be removed. The upper bound of Section 5.1 is , whereas Section 6 rules out only -time algorithms under ETH. For fixed alphabets, the question is whether time is achievable or whether a stronger lower bound holds.
Our analysis shows where this factor comes from and why tuning parameters alone cannot remove it. The exponent in (11) has two parts: enumerating short dictionaries contributes , and enumerating long representatives contributes . For both to be , the former requires , the latter , and these two conditions cannot hold simultaneously as . Thus, the bottleneck is not the choice of but the counting of candidate dictionaries; progress requires a finer count than that of Lemma 5.1.
Conversely, our algorithm bounds the output length of such reductions. For a fixed alphabet, if every N-vertex instance of Vertex Cover of maximum degree at most three could be reduced in polynomial time to a string of length , then our algorithm would yield a -time algorithm for Vertex Cover, contradicting ETH. Our binary reduction has length , which exceeds this limit by a factor of ; the lower bound may therefore be improved, but only by a small factor.
9 Conclusion
Our algorithmic results rest on a structural property: although the rules of an optimal grammar may be arbitrarily nested, its dictionary can always be specified by pairwise disjoint occurrence intervals of the input. This property decouples dictionary enumeration from rule parsing. It yields an exact algorithm running in time, improving the previous bound, as well as a subexponential algorithm over small alphabets and a low-degree polynomial formulation of the decision version of SGP.
The hardness results rely on a different tool: anchors labeled with source symbols are placed in the codewords, and fragments covering several anchors are shown to yield the same labels in all occurrences, so that encoded grammars project back to source grammars. Using this projection and quantitatively relating grammar sizes before and after encoding, we proved that binary SGP is NP-complete, answering a question of Casel et al., and we gave ETH lower bounds governed by , where . A perhaps surprising consequence is that, over fixed alphabets, NP-completeness coexists with subexponential exact algorithms.
The upper and lower bounds leave a gap of in the exponent; closing this gap is the main problem left open.
A Reduction lengths and ETH lower bounds
A.1 General alphabets
Proposition A.1. If ETH holds, SGP over general alphabets has no exact algorithm running in time, where n is the length of the input string.
Proof. By the sparsification lemma [6], it suffices to start from 3-SAT with variables and clauses. After local transformations of constant size, we may assume that every clause contains literals of exactly three distinct variables; after deleting variables that do not occur, , so .
We first construct an Independent Set instance of maximum degree at most three. For a variable occurring times, build an even cycle of length 2d whose vertices alternately represent the values true and false; a variable occurring only once is represented by a single edge. For every clause, build a triangle whose three vertices represent its literals, and connect each of them to the occurrence vertex of the corresponding variable gadget that represents this literal being false. Since different literal occurrences use different vertices, the maximum degree is at most three.
We next bound the size of independent sets. Variable gadgets contribute at most 3m vertices and clause triangles at most m. The total reaches 4m if and only if every variable gadget selects a complete alternating class and every clause selects a true literal, which is exactly equivalent to satisfiability of the formula.
The resulting graph has ; if variables occur only once, then . Finally, we apply the reduction of Charikar et al. [1, Section V-A], which turns this graph into a string of length with
Since , the formula is satisfiable if and only if
The whole reduction has output length . Hence a -time algorithm for SGP would give a subexponential algorithm for sparse 3-SAT, contradicting ETH.
A.2 Fixed alphabets
Observation A.2. If ETH holds, Vertex Cover on graphs of maximum degree at most three has no -time algorithm, where N is the number of vertices.
Proof. The construction in the proof of Proposition A.1 reduces sparse 3-SAT to Independent Set on graphs of linear size and maximum degree at most three. Since complements of independent sets are vertex covers, the lower bound carries over.
The 24-letter reduction of Casel et al. [2] satisfies (22), but Corollary 5.7 also requires its output length, which is not stated explicitly. We derive it from the construction in the conference version [3, Section 3].
Lemma A.3. This reduction satisfies .
Proof. The construction uses centrally palindromic codewords
where is the bijective base-7 representation, so . For the upper bound, all indices are and the total number of codeword occurrences is , so .
For the lower bound, the prefix of the construction contains codewords with indices , each of length ; multiplying gives the matching lower bound.
Section 5.3 takes only a constant number of copies of the source graph and replaces symbols by codewords of constant length; neither step changes the order of magnitude. The final binary instance therefore satisfies
and together with Observation A.2 this gives Corollary 5.7.
B An explicit binary code for 24 letters
Lemma 5.2 proves the existence of synchronizing codes by the probabilistic method; for a deterministic reduction over a fixed alphabet, we list 24 explicit codewords of length 128 and verify boundary synchronization (Section 5.2) by a program. For an ordered pair of symbols , the boundary fragment is
The program exhaustively checks all boundary fragments against all 128 starting phases in the concatenation of every pair of codewords. The output (True, 576) certifies that all boundary fragments are pairwise distinct and that no fragment occurs at a wrong phase or for a wrong pair of symbols, which is exactly property (SI). The listing is also provided as the ancillary file check_sync.py.
CODES = [ "1101111110010010100110111011100010110100000100110110101101101000" "011000000110011111010110001001011000000000101000000100010100011", "1001001011100000110100111111001010100111101110001000111011001010" "110011110100000111000000000110011001101010010000111011110011000111", "10100100111010100100111110011110101101100100000010011110101010" "1000100111000000111001011111100011100101110000000101100111000101", "1110000111011111100001100110100110111001000010101100110101100011" "1011000110000110011001001001110111010010110001000000011000010111", "00011111100010100010001110001000111011100110110111001001101" "1001101101010110010101101011001001111011100001110000111000111111", "0000111011110111101101000111000101000110010011110111010100011111" "1001001000010001011110111110110000101000101010100111110001001001", "1111110010011101111000000101011000100111101011111000001001010011" "0101000110111000110010000010000110100111100011101010111000101101", "1010100101000000100110011011011101110011000001000000010100111001" "0110101011111011101011011100101101110010100100011111111000010101", "1001100000111110111110100011101001001100010101010001011111110101" "0101111011011011000110000101011011001100001001010001011111010000", ]
"1001010101001000111111001000010010110010101111110011010100010010" "1111001100011010010011000000101100011001001110100010000100000010", "1110010100110110110101101110101011000101110110011101011011001011" "101101110100010011100100000000111101101101101111110000000101000", "01110111100000010111001010101101010111110010100111011001010000" "000110111000011100111001101100101111001110111111011010100110011", "1101110100111010010101000100001000001001000011101010101111001001" "0001010100101101110101101011101011010111001111000100010101101100", "101010101010011000000100111100111111000001101001001100011100100" "1110000101101101110100011011110010000100111011100100101101010100", "0100100001011011001101001110001001011011001101011000101110001011" "1011110110001100010001011001111110010000100100010000010100101101", "1000000011111110000000101010011111001011111011111111001010011111" "100110000100001100001011110100001101010010100010001110010111110", "1001111010000110111010000001110100100010010111010000011110100001" "0000101010010111110011111100011000001001111111100111000101100001", "0101111100110010111001011110110111001011010100100110010010111011" "1000001011111100010111111000001000001010011000000111010001000110", "1010000010010100111010011111011001000101100011110111000111010100" "1010000001100001000001111011000100000110111110011000100110100110", "1001111001010011001100001100110100100001111000010000000001011110" "0010111110100000011011011010110110101011011100010110111101100011", "0011101100011101111100100011010101011010000111001110110000101010" "010000100110101000101011011010101111111000110111000100110011111", "0000100110010110011110001111011101110111111110101111001010100100" "0000011011110010001111101110010110101000101100000010000000000110", "0110001100000111110001111100001000011011000110010110001101110101" "0110101011010011001001101000101000011111001101010011100111010001", "000101111111011111010111001010011111100101100001011101111001110" "1000010001100010101101101000111001110011111101010100111111001010",
def check_sync(codes): m, half, window = 128, 32, 64 assert len(codes) == 24 == len(set(codes)) assert all(len(c) == m and set(c) <= {"0", "1"} for c in codes)
fingerprints = {} for a, left in enumerate(codes): for b, right in enumerate(codes): f = left[-half:] + right[:half] if f in fingerprints: return False, ("fingerprint collision", (a, b)) fingerprints[f] = (a, b)
for c, left in enumerate(codes): for d, right in enumerate(codes): joined = left + right for r in range(m): w = joined[r:r + window] if w in fingerprints: if r != m - half or fingerprints[w] != (c, d): return False, ("spurious occurrence", (c, d, r)) return True, len(fingerprints)
print(check_sync(CODES))
Acknowledgements
Use of generative AI. The author delegated the development of the binary-alphabet NP-completeness proof and the reductions establishing the ETH lower bounds to OpenAI GPT-6 Pro, which produced the corresponding derivations and proofs. The polynomial-formulation argument and the resulting SETH-hardness barrier via the theorem of Belova, Golovnev, Kulikov, Mihajlin, and Sharipov (BGKMS), presented in Section 7 and Corollary 1.4, were developed through discussions between the author and OpenAI GPT-5.6 Sol. Generative AI tools were also used for language editing and manuscript preparation. The author takes full responsibility for the mathematical content and the final manuscript.
References
[1] Moses Charikar, Eric Lehman, Ding Liu, Rina Panigrahy, Manoj Prabhakaran, Amit Sahai, and Abhi Shelat. The smallest grammar problem. IEEE Transactions on Information Theory, 51(7):2554–2576, 2005.
[2] Katrin Casel, Henning Fernau, Serge Gaspers, Benjamin Gras, and Markus L. Schmid. On the complexity of the smallest grammar problem over fixed alphabets. Theory of Computing Systems, 65:344–409, 2021. DOI: 10.1007/s00224-020-10013-w.
[3] Katrin Casel, Henning Fernau, Serge Gaspers, Benjamin Gras, and Markus L. Schmid. On the complexity of grammar-based compression over fixed alphabets. In Proceedings of the 43rd International Colloquium on Automata, Languages, and Programming (ICALP 2016), volume 55 of LIPIcs, article 122, 2016. DOI: 10.4230/LIPIcs.ICALP.2016.122.
[4] 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. Preprint: arXiv:2004.01032.
[5] Tatiana Belova, Alexander Golovnev, Alexander S. Kulikov, Ivan Mihajlin, and Denil Sharipov. Polynomial formulations as a barrier for reduction-based hardness proofs. ACM Transactions on Algorithms, 21(4):40:1–40:44, 2025. DOI: 10.1145/3721134. Conference version in SODA 2023; preprint arXiv:2205.07709v5.
[6] Russell Impagliazzo, Ramamohan Paturi, and Francis Zane. Which problems have strongly exponential complexity? Journal of Computer and System Sciences, 63:512–530, 2001. DOI: 10.1006/jcss.2001.1774.
[7] Piotr Masierak. On the binary-alphabet complexity of the assembly index: NP-completeness of ASI-DEC and consequences for SLP and SGP variants. Preprints.org, version 3, 2026. Not peer reviewed. DOI: 10.20944/preprints202602.1964.v3.