Abstract 1 Introduction 2 Preliminaries 3 Upper Bound for Balancing Standard Two-Dimensional SLPs 4 Lower Bound for Balancing without Holes 5 Balancing Two-Dimensional SLPs by Allowing Holes References Appendix A Omitted Proofs Appendix B Many-sorted algebras

Balancing Two-Dimensional Straight-Line Programs

Itai Boneh ORCID Institute of Computer Science, University of Wrocław, Poland    Estéban Gabory ORCID Institute of Computer Science, University of Wrocław, Poland    Paweł Gawrychowski ORCID Institute of Computer Science, University of Wrocław, Poland    Adam Górkiewicz ORCID Institute of Computer Science, University of Wrocław, Poland
Abstract

We consider building, given a straight-line program (SLP) consisting of g productions deriving a two-dimensional string T of size N×N, a structure capable of providing random access to any character of T. For one-dimensional strings, it is now known how to build a structure of size 𝒪(g) that provides random access in 𝒪(logN) time. In fact, it is known that this can be obtained by building an equivalent SLP of size 𝒪(g) and depth 𝒪(logN) [Ganardi, Jeż, Lohrey, JACM 2021]. We consider the analogous question for two-dimensional strings: can we build an equivalent SLP of roughly the same size and small depth?

We show that the answer is negative: there exists an infinite family of two-dimensional strings of size N×N described by a 2D SLP of size g such that any 2D SLP of depth 𝒪(logN) describing the same string must be of size Ω(gN/log3N). We complement this with an upper bound showing how to construct such a 2D SLP of size 𝒪(gN). Next, we observe that one can naturally define a generalization of 2D SLP, which we call 2D SLP with holes. We show that a known general balancing theorem by [Ganardi, Jeż, Lohrey, JACM 2021] immediately implies that, given a 2D SLP of size g deriving a string of size N×N, we can construct a 2D SLP with holes of depth 𝒪(logN) and size 𝒪(g). This allows us to conclude that there is a structure of size 𝒪(g) providing random access in 𝒪(logN) time for such a 2D SLP. Further, this can be extended (analogously as for a 1D SLP) to obtain a structure of size 𝒪(glogϵN) providing random access in 𝒪(logN/loglogN) time, for any ϵ>0. The same (optimal) random access time was very recently achieved by [De and Kempa, SODA 2026], but with a significantly larger structure of size 𝒪(glog2+ϵN).

Keywords and phrases:
Two-dimensional string, straight-line program, random access
Copyright and License:
[Uncaptioned image] © Itai Boneh, Estéban Gabory, Paweł Gawrychowski, and Adam Górkiewicz; licensed under Creative Commons License CC-BY 4.0
2012 ACM Subject Classification:
Theory of computation Pattern matching
Funding:
Partially supported by the Polish National Science Centre grant number 2023/51/B/ST6/01505.
Editors:
Philip Bille and Nicola Prezza

1 Introduction

The goal of the broad area of processing compressed strings is to design algorithms and data structures that operate directly on the compressed representation of a string, with the complexity depending only (or mostly) on its size. This can be of course considered for any problem and any compression method. Perhaps the most basic problem is providing random access, that is, accessing the i-th character of the compressed string efficiently. This is a fundamental prerequisite for more complex questions such as indexing.

Among the plethora of different compression methods, straight-line programs (SLPs) are particularly elegant yet powerful, and algorithms for processing SLP-compressed strings constitute an area of research on their own [18]. Informally speaking, a SLP is simply a context-free grammar on g productions deriving a single string T of length N. A natural approach to providing random access to a SLP is to ensure that its depth is small, and then just implement random access by traversing the grammar in time bounded by its depth. While it was known how to guarantee that the depth is 𝒪(logN) at the expense of increasing the size of the grammar by a logarithmic factor [20, 10], it was not clear if such an increase in the size is necessary. However, Bille et al. [6] settled the complexity of providing random access to a SLP by describing a structure of size 𝒪(g) with query time 𝒪(logN) (in the Word RAM model; see [5] for an alternative solution in the weaker pointer machine model). This should be compared with a lower bound of Verbin and Yu [23]: there exists an infinite family of SLPs on g productions describing strings of length N=g1+ϵ such that, for any structure of size 𝒪(gpolylogN), the query time needs to be Ω(logN/loglogN). Thus, the only remaining question is whether we can design a structure of size 𝒪(g) and query time 𝒪(logN/loglogN).

The structure of Bille et al. requires carefully combining quite a few tools. Somewhat surprisingly, Ganardi, Jeż, and Lohrey [14] showed that this is not necessary: one can always build an equivalent SLP (describing the same string) of size 𝒪(g) and depth 𝒪(logN). With such a grammar in hand, random access can be directly implemented in 𝒪(logN) by simply storing the length of the expansion of each nonterminal and traversing the grammar down from the starting nonterminal. Further, one can easily obtain a structure of size 𝒪(glogϵN) and optimal query time 𝒪(logN/loglogN) by “unwinding” the first Θ(loglogN) levels of the derivation of each nonterminal, and storing the information about the obtained sequence of nonterminals in a fusion tree [12].

In this paper, we consider a two-dimensional string, which is simply a rectangular array of characters of size N×M. Such objects have been studied in the area of formal languages [16]. Lempel and Ziv [17] defined a compression scheme for 2D strings by proceeding similarly as for 1D strings, and informally speaking keeping only the first occurrence of each substring while replacing its further occurrences by pointers to the first occurrence. However, this is not necessarily convenient for providing efficient random access, which led Brisaboa et al. [7] to introduce 2D block trees that do allow for efficient random access at the expense of restricting which occurrences are being replaced (and no clear bound on the size of the compressed representation; see [8] for an attempt at providing one). Another natural possibility is to generalize context-free grammars to two-dimensional strings, by allowing productions of the form AB and AB, denoting the horizontal and the vertical concatenation, respectively. For every such production, the corresponding dimensions of all strings derived from both nonterminals must be equal. Such a generalization appears to have been introduced multiple times in the literature [19, 21, 22]. This leads to the notion of a 2D SLP, which is such a context-free grammar that derives exactly one 2D string.

Berman et al. [4] showed that many problems that can be efficiently solved on 1D SLPs become intractable on 2D SLPs. For example, compressed pattern matching (where the pattern is uncompressed but the text is compressed) for 2D strings is NP-complete, but linear-time for 1D SLP-compressed texts [13] or 2D RLE-compressed texts [2]. However, for random access this is not the case: very recently, De and Kempa [11] showed how to construct a structure of size 𝒪(glog2+ϵN) with query time 𝒪(logN/loglogN) (for NM). Carfagna et al. [9] observed that, in fact, the structure of Bille et al. can be (informally speaking) applied on each dimension separately, resulting in a structure of size 𝒪(g) and query time 𝒪(logN).

Balancing 2D SLPs.

We study the problem of balancing 2D SLPs. Our first result is a simple upper bound, showing that given a 2D SLP of size g deriving a string of size N×M (for NM) we can construct a 2D SLP of size 𝒪(gM) and depth 𝒪(logN). This is, of course, a significant increase in the size for highly compressible strings. A natural question is whether we could, similarly to 1D SLPs, achieve the same balancing without increasing the SLP size. Namely, given a 2D SLP on g productions deriving a string of size N×M (for NM), is there a 2D SLP on 𝒪(g) productions deriving the same string but of depth 𝒪(logN)? We give a negative answer to this question, showing that for infinitely many values of N there exists an N×N 2D string described by a 2D SLP of size g, such that any 2D SLP of depth 𝒪(logN) describing the same string must consist of Ω(gN/log3N) productions.

Figure 1: 2D SLP with holes allows horizontal concatenation AB (top left), vertical concatenation AB (bottom left), and substitution A(B) . The dashed rectangle represents the hole that might be present in at most one argument of a concatenation, and might be present in B (and needs to be present in A) for a substitution A(B). Further, the corresponding dimensions always need to match.

2D SLPs with holes.

To overcome this barrier, we define a natural generalization of 2D SLPs: 2D SLPs with holes. In such a SLP, a nonterminal can also derive a 2D string from which a rectangular fragment has been removed. One can then naturally define the productions as either horizontal or vertical concatenations of two nonterminals in which at most one has a hole, and substituting the string (with or without a hole) derived by a nonterminal into the hole of the string derived by another nonterminal, see Figure 1. Then, given a 2D SLP with holes of depth d, we can implement random access in 𝒪(d) time by simply storing, for every nonterminal, the size of its derived string together with the position of its hole (if one exists). Now, given a 2D SLP of size g deriving a 2D string of size N×M (for NM), we would like to construct a balanced 2D SLP with holes deriving exactly the same string. We observe that the general balancing theorem of Ganardi, Jeż, and Lohrey [14] immediately implies that one can obtain such a 2D SLP with holes of size 𝒪(g) and depth 𝒪(logN). Next, by “unwinding” the first Θ(loglogN) levels of the derivation of each nonterminal, this allows us to obtain a structure of size 𝒪(glogϵN) and query time 𝒪(logN/loglogN), for any ϵ>0, in the Word RAM model. Such query time is optimal for structures of size 𝒪(gpolylogN) by applying the lower bound for 1D SLPs, and our space is smaller by two factors of logN compared to the recent result of De and Kempa [11], matching the best known bounds for 1D SLPs [3].

2 Preliminaries

Integer intervals.

For integers i,j, we denote [i..j]={i,i+1,,j} ([i..j]= for j<i), and [i]=[1..i]. We also denote (i1..j+1)=[i..j+1)=(i1..j]=[i..j].

Strings.

Let Σ be a fixed finite alphabet. A string S=S[1]S[2]S[N] of length N is a sequence of N characters from Σ. For i,j[N], we define a substring X of S as X=S[i..j]=S[i]S[i+1]S[j]. If i=1 or j=N, the substring X is called a prefix or a suffix of S, respectively.

2D strings.

An N×M two-dimensional (2D) string S is an N×M array of characters from Σ. We write h(S) to denote the number of rows N, and w(S) to denote the number of columns M. We also write dim(S) to denote the pair (N,M). Similarly to 1D strings, we define a substring of S as X=S[i..j][i..j] for some i,j[N] and i,j[M]. For every i[N], we define S[i]=S[i][1..M] as the i-th row of S. We observe that S[i] is a string. Given two 2D strings A, B, we define their horizontal concatenation AB when h(A)=h(B) and their vertical concatenation AB when w(A)=w(B) in the natural way. We sometimes interchangeably view one-dimensional (1D) strings of length N as 1×N strings, and elements of Σ as 1×1 strings. For a more detailed introduction on 2D strings and languages, see [16].

2D SLP.

A 2D straight-line program 𝒢 is a grammar (𝒱,𝒮,ρ) where:

  • 𝒱 is a set of nonterminals, with 𝒱Σ=. Each X𝒱 has a dimension dim(X)=(h(X),w(X)) indicating that it derives a string of size h(X)×w(X).

  • 𝒮𝒱 is called the starting nonterminal.

  • ρ is a mapping on the set 𝒱, where ρ(X) is one of the following:

    • σ, where σΣ, and h(X)=w(X)=1,

    • YZ, where Y,Z𝒱, h(X)=h(Y)=h(Z), w(X)=w(Y)+w(Z),

    • YZ, where Y,Z𝒱, w(X)=w(Y)=w(Z), h(X)=h(Y)+h(Z).

    We call the pair (X,ρ(X)) a production, with X being its left-hand side and ρ(X) its right-hand side. We require that the relation on 𝒱 defined by XY if Y appears in the right-hand side of X must be acyclic. We will sometimes allow a production ρ(X) to be any string over Σ𝒱, and then normalize the grammar in the standard way.

From the acyclicity condition, it follows that for each nonterminal X𝒱, there is a unique 2D string Exp𝒢(X) (or simply Exp(X) if 𝒢 is clear from the context), called the expansion of X, derived from X by recursively replacing each nonterminal in the right-hand side of its production by the corresponding derived string. This process can be described as a tree 𝒯𝒢, called the derivation tree of 𝒢. Every internal node in 𝒯𝒢 is labeled with a nonterminal of 𝒢, while each leaf is labeled with a symbol from Σ. The root corresponds to the starting nonterminal 𝒮. The children of a node labeled with a nonterminal X𝒱 correspond to the nonterminals that appear in ρ(X), or a letter σΣ if ρ(X)=σ.

The 2D string derived by the SLP is denoted by Exp(𝒢)=Exp𝒢(𝒮). The size |𝒢| is the total number of symbols on the right-hand sides of all productions, and the depth of 𝒢 is the depth of 𝒯𝒢. Notice that there is a 1-1 correspondence between the leaves of 𝒯𝒢 and the positions in Exp(𝒢).

We view one-dimensional SLPs as a special case of 2D SLPs that use only horizontal concatenations and derive strings of height 1.

Fusion trees.

For efficient random access on 2D strings, we need predecessor queries and fusion trees. Let S[U] be a set of integers. A predecessor query on S takes as input an integer x[U] and returns the largest integer yS such that yx. We have the following result in the Word RAM model.

Lemma 1 ([12]).

Given a set S of k integers from [U], one can build in time 𝒪(k) a data structure of size 𝒪(k), called a fusion tree, that allows predecessor queries in 𝒪(logk/loglogU) time.

3 Upper Bound for Balancing Standard Two-Dimensional SLPs

The goal of this section is to prove the following theorem. For notational convenience, we assume NM, and by transposing the input we obtain the statement from the introduction.

Theorem 2.

Given a 2D SLP 𝒢 deriving a string TΣN×M (for NM), one can construct an equivalent 2D SLP of size 𝒪(|𝒢|N) and depth 𝒪(logM).

We first introduce a simple tool for when we want to concatenate multiple nonterminals.

Proposition 3 (Concatenation gadget).

Let X1,X2,,Xk be nonterminals of a 2D SLP with expansions of the same height (horizontal case) or width (vertical case). Then one can introduce a new nonterminal Y with

Exp(Y)={Exp(X1)Exp(Xk),(horizontal case),Exp(X1)Exp(Xk),(vertical case),

using 𝒪(k) additional nonterminals arranged as a balanced binary tree. This increases the total size of the grammar by 𝒪(k) and the overall depth by 𝒪(logk). Importantly, when multiple such gadgets are added independently (that is, their roots do not appear in each other’s subtrees), the total increase in depth remains bounded by the maximum of their individual increases, not their sum.

The proof of Theorem 2 proceeds in three steps: (i) turn 𝒢 into a 1D SLP of size 𝒪(|𝒢|N) deriving the concatenation of the rows; (ii) balance this SLP using [14]; (iii) reconstruct the original 2D layout while preserving logarithmic depth.

The next lemma performs the first step of the construction.

Lemma 4.

Given a 2D SLP 𝒢 deriving a string TΣN×M (for NM), one can construct a 1D SLP of size 𝒪(|𝒢|N) deriving the concatenation of all rows of T, that is,

T[1]T[2]T[N]Σ1×NM,

where T[i] denotes the i-th row of T.

Proof.

Let 𝒢=(𝒱,𝒮,ρ) be the given grammar. For each X𝒱 we introduce nonterminals X1,X2,,Xh(X). The goal is to construct a 1D SLP 𝒢=(𝒱,𝒮,ρ) over all the introduced nonterminals, so that for every X𝒱 and i[h(X)] we have

Exp𝒢(Xi)=Exp𝒢(X)[i].

We first set 𝒱{Xi:X𝒱,i[h(X)]}{𝒮}, where 𝒮 is a new starting nonterminal. Since each nonterminal X introduces at most h(X)N new nonterminals, we have |𝒱|=𝒪(|𝒱|N). The productions ρ(Xi) are defined depending on the production ρ(X):

  1. 1.

    if ρ(X)=σΣ, then ρ(X1)σ,

  2. 2.

    if ρ(X)=AB, then ρ(Xi)AiBi,

  3. 3.

    if ρ(X)=AB and ih(A), then ρ(Xi)Ai,

  4. 4.

    if ρ(X)=AB and i>h(A), then ρ(Xi)Bih(A).

To define ρ(𝒮) as the horizontal concatenation of 𝒮1,𝒮2,,𝒮N, we use the concatenation gadget (Proposition 3), adding 𝒪(N) to the overall size of 𝒢. It follows by induction that for every X𝒱 and i[h(X)], Exp𝒢(Xi)=Exp𝒢(X)[i], and thus Exp𝒢(𝒮)=T[1]T[2]T[N].

We now proceed with the proof of Theorem 2. Let 𝒢 be a 2D SLP deriving a string T of size N×M (for NM). We apply Lemma 4 and then balance the resulting 1D SLP.

Theorem 5 ([14, Theorem 1.2]).

Given a 1D SLP 𝒢 deriving a string of length N, one can construct an equivalent 1D SLP of size 𝒪(|𝒢|) and depth 𝒪(logN).

We obtain a 1D SLP 𝒢=(𝒱,𝒮,ρ) of size 𝒪(|𝒢|N) and depth 𝒪(logM), deriving

T[1]T[2]T[N]Σ1×NM.

We view 𝒢 as a 2D SLP that uses only horizontal concatenations. We will now modify it, so that it again derives the original 2D string T while maintaining its logarithmic depth.

Lemma 6 (Folklore).

Let be a 1D SLP of depth d deriving a string S. Any substring of S can be expressed as a concatenation of 𝒪(d) expansions of nonterminals of .

Proof.

Take any substring from position i to j. In the derivation tree of let u be the lowest common ancestor of the i-th and j-th leaf. Along the two root-to-leaf paths from u, take the siblings hanging to the right of the left path and to the left of the right path, together with the i-th and the j-th leaf. The concatenation of these 𝒪(d) nonterminals expands to the whole substring.

Since every row T[i] is a substring of Exp(𝒢), we can use Lemma 6 to identify 𝒪(logM) nonterminals X1,X2,,Xk, such that

T[i]=Exp𝒢(X1)Exp𝒢(X2)Exp𝒢(Xk).

Then, for each i, we introduce a new nonterminal Ri by applying Proposition 3 to X1,,Xk, implementing the production

ρ(Ri)X1X2Xk.

Each gadget increases the depth by 𝒪(loglogM) and creates 𝒪(logM) new symbols, but since the Ri’s are created independently (none of them occurs in another’s subtree), the overall depth of the grammar increases by only 𝒪(loglogM) altogether. The total increase in size is 𝒪(NlogM), which is 𝒪(|𝒢|N), because of the straightforward lower bound of Ω(logM) on the size of 𝒢.

Finally, we introduce a new starting nonterminal 𝒮′′ with the production

ρ(𝒮′′)R1R2RN,

constructed using Proposition 3, adding 𝒪(N) to the size and 𝒪(logN) to the depth of 𝒢. Then

Exp𝒢(𝒮′′)=Exp𝒢(R1)Exp𝒢(RN)=T[1]T[N]=T.

The resulting grammar has size 𝒪(|𝒢|N), and depth 𝒪(logM).

4 Lower Bound for Balancing without Holes

In this section, we prove that the linear multiplicative blowup of Theorem 2 is essentially unavoidable in the general case. Formally, we prove the following.

Theorem 7.

For every integer c, there are infinitely many integers N for which there exists a 2D SLP 𝒢 with g nonterminals deriving a string SΣN×N such that any 2D SLP deriving S has either depth at least clogN or Ω(gNlog3N) nonterminals.

We begin by presenting some gadgets that will be useful for proving Theorem 7. Intuitively, our goal is to obtain a highly compressible 2D string such that most of its rows correspond to very non-compressible 1D strings. Our construction can be seen as a stronger variant of the gadget used by Berman et al. [4, Theorem 2.2] (using their gadget directly would only allow us to obtain a lower bound of roughly Ω(gN) in Theorem 7).

Definition 8 (See Figure 2).

For every N=2n, we define 𝖡𝗂𝗇N as a 2D string with dimensions N×(n+2) in which the i-th row is the n-bit binary representation of i1, surrounded by $ symbols. Next, we define 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇N as a binary 2D string with dimensions 2N×N(n+2) such that for every i[0..N1], the substring 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇N[1..2N][i(n+2)+1..(i+1)(n+2)] contains a copy of 𝖡𝗂𝗇N in the i’th row, and the rows not contained within an occurrence of BinN are all zeros.

Figure 2: Left: 𝖡𝗂𝗇8, right: 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇8 (the gray area is all 0s).

We observe that 𝖡𝗂𝗇N and (more importantly) 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇N are highly compressible. The proof of the following lemma can be found in Appendix A.

Lemma 9.

For every N=2n, there is a 2D SLP with 𝒪(n) nonterminals deriving 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇N.

Even though 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇N is highly compressible, it contains very incompressible 1D strings. In the following lemma, we show that the central rows of 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇N (i.e., rows that are a constant fraction of the height of 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇N away from the top and bottom) are highly incompressible.

Lemma 10.

For every N=2n, and i[2N], denote as RN,i the i-th row of 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇N. Any (1D) SLP deriving a superstring of RN,i is of size at least min{i,2Ni+1}.

Proof.

Observe that the string RN,i contains substrings of the form $b$ where b is the logN-bit binary encoding of some number zb. Specifically, RN,i contains such substrings for min{i,2Ni+1} distinct values of zb.

Let 𝒢 be a grammar deriving a superstring of RN,i. For every zb such that $b$ is a substring of RN,i, denote as A(zb) the minimal nonterminal of 𝒢 that expands to a superstring of $b$. That is, A(zb) is a nonterminal expanding to a string containing $b$ as a substring, with rule ρ(A(zb))=BC such that neither B nor C contains $b$ as a substring.

We claim that for every two distinct zb,zb, it holds that A(zb)A(zb). Indeed, ρ(A(zb))=BC such that Exp(B) has a suffix of the form $b1 and Exp(C) has a prefix of the form b2$ satisfying b=b1b2. Similarly, ρ(A(zb))=BC such that B has suffix $b1 and C has prefix b2$ satisfying b=b1b2. Since bb and $ does not occur in b or b, it cannot be the case that A(zb)=A(zb). We have shown that 𝒢 contains a distinct nonterminal for every one of the min{i,2Ni+1} different values of zb, which concludes the proof.

Next, we show that a 2D grammar deriving a string S implies a 1D grammar of similar size deriving the margins of S.

Lemma 11.

Let S be a 2D string and let t, b (resp. , r) be the top and bottom rows (resp. left and right columns) of S. Let 𝒢=(𝒱,𝒮,ρ) be a 2D SLP deriving S. There are 1D SLPs deriving t, b, , and r, each of size at most |𝒢|.

Proof.

We show how to construct a grammar for t, the remaining cases are symmetric.

We create 1D SLP 𝒢 with nonterminals 𝒱={A:A𝒱}. For every nonterminal A𝒱, if ρ(A)=BC, we set ρ(A)B (i.e., keeping just the top part of Exp(A)). If ρ(A)=BC, we set ρ(A)BC. If ρ(A)=σ for some terminal σ, we set ρ(A)σ.

It is clear that |𝒢||𝒢|, and it can be verified (for example, by induction) that 𝒢 derives the top row of S, as required.

Let us define the main gadget used for proving Theorem 7.

Definition 12 (See Figure 3).

For every N,M, we define a 2D string CN,M with dimensions N×M. Choose the largest M=2n such that M(logM+2)M/2 and let B=𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇M. CN,M contains two vertical blocks: The left block is formed by N2M vertically concatenated copies of B. The right block is formed by NM2M vertically concatenated copies of B, shifted vertically by M positions. Each block is padded with 0 symbols so that its total height equals N. Finally, to the right of the blocks there is a padding of 0 symbols to complete the width to M.

Figure 3: A demonstration of CN,M. Each rectangle with a diagonal pattern is a copy of 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇M (the diagonal pattern corresponds to the shifted copies of 𝖡𝗂𝗇M within 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇M). The gray areas are the padding 0s used to “shift” the second vertical block, and the extra vertical padding at the bottom to complement the height of each vertical block to N.

Recall that the width of 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇M is M(logM+2). Therefore, the width of each vertical block is M(logM+2)M/2, so the combined width of the first two blocks never exceeds M. Also recall that the height of 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇M is 2M, so each block contains the maximal number of vertically concatenated copies of 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇M that fit within height N (for the right block, this takes into account the initial vertical shift of M positions).

We proceed to show that there is a logarithmic sized 2D SLP deriving CN,M.

Lemma 13.

For every N,M, there is a 2D SLP of size 𝒪(logN+logM) deriving CN,M.

Proof.

Each of the two blocks of CN,M can be produced by starting with a grammar of size 𝒪(logM) that derives B, and adding 𝒪(log(N/M)) nonterminals that produce concatenations of exponentially increasing amounts of B. Then, to get a block of CN,M we can concatenate 𝒪(log(N/M)) such nonterminals. The 0 paddings can be obtained using additional 𝒪(logN+logM) nonterminals.

In our lower bound construction, we are interested in constructing a grammar with nonterminals producing a sequence of k+1 gadgets of the form

CN,M,CN+b,M,CN+2b,M,,CN+kb,M

for some b that is an integer multiple of M. In the following lemma, we show that nonterminals producing such sequence can be constructed using a small amount of additional nonterminals.

Lemma 14.

Let N,M and choose the largest M=2n such that M(logM+2)M/2. Let bN be some integer multiple of M and let k. There is a grammar 𝒢 satisfying the following.

  1. 1.

    For every i[0..k], 𝒢 contains a nonterminal Ci that expands to CN+ib,M.

  2. 2.

    𝒢 contains 𝒪(logN+logM+k) nonterminals in total.

Proof.

We will show how to construct a grammar with the required amount of nonterminals, containing Ci for even values of i. A similar grammar can be constructed for odd values of i, and the union of the two grammars satisfies the required conditions. For an integer N, we denote the following substrings of CN,M:

  1. 1.

    BN1 is the left vertical block of CN,M, without the vertical padding to complement the height to N.

  2. 2.

    BN2 is defined identically to BN1, but for the right block of CN,M.

  3. 3.

    BN3 is the horizontal padding to complement the width of CN,M to M.

  4. 4.

    PN1 is the vertical padding at the bottom of the left vertical block.

  5. 5.

    PN2 is the vertical padding at the bottom of the right vertical block.

We observe that PN1 and PN2 are all-0s strings, and their dimensions depend only on the remainder of N modulo 2M. Therefore, PN1=PN+2b1 and PN2=PN+2b2. We also observe that BN+2b1 is obtained from BN1 by appending b/M copies of 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇M to the bottom of BN1, and the same is true for BN2 and BN+2b2. Finally, BN+2b3 is obtained from BN3 by appending a block of 0’s with height 2b and appropriate width.

Let 𝒢N,M be the grammar deriving CN,M as described in Lemma 13. Recall that the grammar 𝒢N,M has nonterminals generating each of BN1, BN2, BN3, PN1 and PN2. We extend 𝒢N,M to include the following nonterminals:

  1. 1.

    V1: a vertical concatenation of b/M copies of 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇M.

  2. 2.

    V2: an all-0s block with height 2b and width w(BN3).

Observe that both V1 and V2 can be added to the grammar using 𝒪(logN+logM) additional nonterminals. It follows from the above discussion that if we have a grammar with nonterminals expanding to BN1, BN2, BN3, PN1 and PN2, we can add 𝒪(1) nonterminals to obtain nonterminals expanding to BN+2b1, BN+2b2, BN+2b3, PN+2b1, and PN+2b2. Then, a nonterminal CN+2b can be added by adding additional 𝒪(1) nonterminals concatenating the above appropriately. By repeating this process k/2 times, we obtain a grammar containing CN+ib,M for every even i in [0..k]. The total number of nonterminals is 𝒪(logN+logM+k), as required.

We are now ready to prove Theorem 7.

Proof of Theorem 7.

Let us start by providing some intuition. We will construct a string S that is composed of instances of CN,M with MΘ(NlogN). The instances are nested in a spiral manner with decreasing lengths (see Figure 4). The ’depth’ of this spiral (i.e., number of swirls before the center is reached) will be roughly clogN. Since every ’step’ in this pattern is a CN,M gadget with N,M𝒪(N), a grammar 𝒢 deriving S can be easily constructed using 𝒪(log2N) nonterminals. We will actually show how to construct such a grammar with 𝒪(logN) nonterminals.

To understand the intuition behind this construction, think of a 2D SLP 𝒢 deriving S with a small number of nonterminals (i. e. , |𝒢|o(Nlog2N) ). Think of a path P in the derivation tree of 𝒢 from the root to some index at the center of S. It is helpful to think of P as a sequence of nested rectangles in S, all containing the center point of S. Intuitively, each of the CN,M gadgets limits the structure of these rectangles. Namely, these rectangles cannot horizontally intersect a CN,M gadget (except possibly very close to the top/bottom of said gadget), as this would imply that the top/bottom of a rectangle contains some row of a 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇 gadget as a substring. By Lemma 10 and Lemma 11, a nonterminal that expands to a string with such a top/bottom row requires a large number of nonterminals, contradicting the small size of 𝒢. It follows that the rectangles of P have to roughly comply with the structure of the spiral. This allows us to lower bound |P|, and thus the depth of 𝒢.

We proceed to define 𝒢 and S. Let Δ=N8clogN and λ=2clogN. Let M be the largest power of 2 such that M(logM+2)Δ/2. Let Δ be the largest integer smaller than Δ that is an integer multiple of M. Notice that we must have Δ[Δ/2..Δ] since Δ2M and ΔΔM. Also observe that M′′, the largest power of two such that M′′(logM′′+2)Δ, must be exactly M′′=M (otherwise, 2M(logM+2) is an integer multiple of M strictly between Δ and Δ).

For an integer N, let C~N,Δ denote the string CN,Δ rotated clockwise by 90 degrees. We denote as G(N) and G~(N) the nonterminals that expand to CN,Δ and C~N,Δ, respectively.

We define the SLP 𝒢=(𝒱,F00,ρ) as follows. For every i[0..λ1] and x{0,1,2,3} there is a nonterminal Fix in 𝒱 with the following derivation rules (see Figure 4 for a demonstration):

  1. 1.

    ρ(Fi0)Fi1G(N2iΔ) for every i[0..λ1],

  2. 2.

    ρ(Fi1)Fi2G~(N(2i+1)Δ) for every i[0..λ1],

  3. 3.

    ρ(Fi2)G(N(2i+1)Δ)Fi3 for every i[0..λ1],

  4. 4.

    ρ(Fi3)G~(N(2i+2)Δ)Fi+10 for every i[0..λ2].

Figure 4: A demonstration of the string S obtained by the described grammar. The grammar composes rotated copies of CN,M in a spiral pattern. The narrow dimension of each gadget is always Δ=N8clogN, and the wide dimension decreases as the spiral swirls inwards.

Finally, Fλ13 expands to a string of size N4λΔ×N4λΔ filled with 0s (notice that N4λΔN4λΔ=N/2). The starting nonterminal of 𝒢 is F00, which expands to the string S. In words, the nonterminals alternate between expanding to a CN,Δ gadget, and expanding to a C~N,Δ gadget. The width (or height, if rotated) of the gadgets is always Δ, and the height N (if rotated, width) decreases to fit the remaining height/width of S.

It follows from Lemma 14 that all G and G~ nonterminals used in the construction defined above can be created using 𝒪(logN+logΔ+λ)=𝒪(logN) nonterminals. Clearly, the all-0s string of Fλ13 can also be produced using 𝒪(logN) nonterminals. The total number of nonterminals in the grammar is therefore n=𝒪(logN). For every i[0..λ1], we call the string produced by Fi0 the i-th layer of S, denoted by Li. In terms of indices in S, the i-th layer of S is defined as Li=S(iΔ..NiΔ](iΔ..NiΔ]. The Δ right columns of Li are an occurrence of CN,Δ with N=N2iΔ being the height of Li.

We proceed to prove that no grammar 𝒢 with o(N/log2N) nonterminals and depth less than clogN can derive S. Assume to the contrary that such a grammar 𝒢=(𝒱,𝒮,ρ) exists. For any nonterminal X𝒱 and i[λ], we say that the nonterminal X contains Li if it expands to S[x..x][y..y] such that (iΔ..NiΔ][x..x][y..y], i.e., Exp𝒢(X) is a superstring of Li. Let P=V1,V2,Vd be the sequence of nonterminals obtained by traversing the derivation tree 𝒯𝒢 from the root to the leaf corresponding to position (N/2,N/2). Notice that position (N/2,N/2) is contained in all λ layers of S. For every i[λ/2], let Xi be the last nonterminal in P whose expansion contains L2i. Since V1 expands to S, which contains all layers of S, all Xi’s are well defined. We show that for every i[λ/21], Xi strictly precedes Xi+1 in P, which implies that |P|λ/2=clogN, contradicting d<clogN.

Claim 15.

For every i[λ/21], Xi strictly precedes Xi+1 in P.

Proof.

Since L2i contains L2(i+1) as a substring, it is clear that Xi weakly precedes Xi+1 in P. Assume to the contrary that Xi does not strictly precede Xi+1, which implies Xi=Xi+1. Let X=Xi=Xi+1, and let the production rule of X be ρ(X)=BC. Assume that the production rule of X is a vertical concatenation rule, as the other case (horizontal concatenation rule) is symmetric. Note that it is impossible for the production rule of X to be ρ(X)=σ for some terminal σ, as Exp𝒢(X) contains L2i.

We will show that the bottom row of B contains a row of L2i that is not-too-close to the margins of L2i (See Figure 5). Specifically, we will show that the bottom row of B contains the z~-th row of L2i with z~ being at distance at least 2Δ from the top and the bottom of L2i.

Figure 5: A visualization of the proof of Theorem 7. The outer rectangle represents the expansion of X. The indices depicted to the left and above the outer rectangle represent absolute positions of the corresponding substrings within S. The dashed horizontal cut represents the derivation rule of X. Due to X being the last nonterminal containing L2(i+1) (represented as a light gray square), this cut must intersect L2(i+1), as depicted. The gray rectangles represent the CN,M gadgets that form the frame of L2i. Since the cut intersects L2(i+1), it intersects a vertical CN,M gadget of L2i not-too-close to the boundaries (L2i+1 functions as a ’buffer’ layer between the L2i and L2(i+1), assuring that the cut is not within the first of the last 2Δ rows of L2i). The dark gray row is a row of some CN,M gadget which is a substring of the bottom row of B (and the z~-th row of the gadget).

Let the string Exp𝒢(X) be SX=S[x..x][y..y]. Since SX contains L2i, it holds that (2iΔ..N2iΔ][x..x][y..y]. We claim that both B and C do not contain L2i+2. If X=V and V+1=B, we have that B does not contain L2i+2 by the maximality of V in the sequence P. Recall that the position (N/2,N/2) is contained in B (and not in C). This implies that Exp𝒢(C) does not contain the unique square of 0s with dimensions N2λΔ×N2λΔ at the center of S, which is a necessary condition for containing any layer of S. Symmetric arguments can be made if V+1=C.

Intuitively, the fact that both B and C do not contain L2i+2 means that the production rule ρ(X)=BC “cuts” the occurrence of L2i+2 within SX. Formally, let SB denote Exp𝒢(B). It holds that SB=S[x..z][y..y] for some z((2i+2)Δ..N(2i+2)Δ]. Consider the bottom row of SB i.e. S[z][y..y]. Since the interval [y..y] contains the horizontal span of L2i, the bottom row S[z][y..y] of B contains the z~-th row of L2i, with z~=z2iΔ. Indeed, we have z~(2Δ..N(4i+2)Δ], and in particular z~(2Δ..h2Δ] with h=N4iΔ being the height of L2i. It follows that S[z][y..y] contains the z~-th row of C=CN4iΔ,Δ, which constitutes the rightmost Δ columns of L2i.

Let us focus on R, the z~-th row of C (See Figure 6). Recall that we took the largest M=2n such that M(logM+2)Δ/2. Due to the maximality of M, we have 2M(log2M+2)>Δ/2 which implies MΩ(ΔlogN)=Ω(Nlog2N). Recall that C is composed of two vertical blocks, each block consists of a vertical concatenation of 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇M gadgets with dimensions 2M×M(logM+2). In the first block, every row except possibly the last 2M1 rows is a row of some 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇M gadget. In the second block, every row except the first M rows and the last 2M1 rows is a row of some 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇M gadget. We have 2MMlogMΔ/22Δ (the first inequality assumes M4, which occurs for a sufficiently large N). It follows that [2Δ..h2Δ][2M..h2M] and therefore z~[2M..h2M].

We have shown that R contains a row of 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇M in both blocks of C. Assume that R contains the r-th row of a 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇M in the left block of C. Due to the right block being vertically shifted by M compared to the left block, the row of 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇M contained in R from the second block of C is r=r+Mmod2M. One can verify that one of r,r must be in [M/2..3M/2], assume without loss of generality that r[M/2..3M/2]. According to Lemma 11 there is a 1D grammar deriving R with n nonterminals such that n is the number of nonterminals in 𝒢. Since R is a superstring of the r-th row of 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇M, Lemma 10 yields nmin{r,2Mr}M/2Ω(Nlog2N), a contradiction to no(Nlog2N).

In conclusion, every 2D SLP deriving S has either depth at least clogN or Ω(Nlog2N)=Ω(|𝒢|Nlog3N) nonterminals (recall that |𝒢|𝒪(logN)), as required.

Figure 6: A demonstration of the z~ row of C=CΔ,N4Δ (the third padding block is ignored here). The white rectangle represents the ’padding’ zeros added to each block of C, the grey area in each row is tiled with occurrences of 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇b. Since z~ is at least 2b indices away from the top/bottom of the gadget, the z~-th row is contained in the gray areas of both rows.

5 Balancing Two-Dimensional SLPs by Allowing Holes

As shown in Theorem 7, it is not always possible to balance 2D SLPs while keeping their size small. To overcome this limitation, we next introduce two-dimensional tree straight-line programs (2D TSLPs), or 2D SLPs with holes, which are a generalization of 2D SLPs that allow contexts in the derived objects (for clarity, standard 2D strings are called ground 2D strings). Intuitively, a context is a 2D string S defined over a frame (a rectangle from which a smaller p×q rectangle has been removed). It corresponds to a function mapping a 2D string T of size p×q to the string S(T) obtained by filling the hole of S with T. A 2D TSLP also allows extra productions, corresponding to context evaluation, composition, and concatenation of a context with a ground 2D string (see Figure 1). We then apply a theorem from [14], stating that from any SLP, one can construct an equivalent balanced TSLP having the same size. Using this balanced representation, we then describe a data structure providing efficient random access on a 2D string.

The result of [14] is based on the more general setting of (many-sorted) algebras. We briefly recall the relevant notions; the complete formal treatment is deferred to Appendix B. A many-sorted algebra (A,Γ) is given by a family of sets Ass𝒮 indexed by sorts s𝒮, and a set Γ of functions f:Ap1××AprAq that respect the sorts. We call r the rank of f. An SLP over (A,Γ) assigns to each nonterminal X a sort s, and each production is either a constant aAs or a function application f(T1,,Tr) with arguments of the correct sorts. A context is obtained from a function by fixing all but one argument, e.g. f(a1,,ai1,,ai+1,,ar), and represents a map from sort pi to sort q. A TSLP extends an SLP by introducing context nonterminals that derive such contexts, together with productions for context application, composition, and insertion into function arguments.

Theorem 16 ([14, Remark 3.27]).

Let (A,Γ) be a many-sorted algebra and let 𝒢 be a TSLP over (A,Γ) deriving tA. One can in time 𝒪(|𝒢|) compute an equivalent TSLP over (A,Γ) of size 𝒪(r|𝒢|), and depth 𝒪(log|t|), where r is the maximal rank of a function in Γ.

2D SLPs with holes.

We instantiate this framework to 2D strings as follows. The set of sorts 𝒮 is ×, where a sort (h,w) corresponds to 2D strings of height h and width w over the alphabet Σ. The functions in Γ are the rank-2 horizontal and vertical concatenation operations (formally, Γ contains one horizontal (resp. vertical) concatenation for each pair of compatible dimensions, but we omit this distinction). In that setting, context nonterminals can be seen as 2D strings with a hole, that can be filled with another 2D string of appropriate dimensions.

A 2D TSLP is then a TSLP over the many-sorted algebra (A,Γ). Concretely, it consists of a set 𝒱=𝒱G𝒱C of nonterminals where each ground nonterminal X𝒱G has a sort (p,q), meaning it derives an ordinary p×q 2D string, and each context nonterminal C𝒱C has a pair of sorts ((p,q),(p,q)), meaning it derives a context that takes a p×q string and returns a p×q string. In other words, C derives a 2D string of dimensions p×q with a hole of dimensions p×q that can be filled by another 2D string of matching dimensions.

Productions are of the following forms:

  • Ground productions:

    • ρ(X)=σ where σΣ (a 1×1 string);

    • ρ(X)=YZ or XYZ with Y,Z𝒱G of appropriate dimensions;

    • ρ(X)=C(Y), where C𝒱C derives a context whose hole matches the dimension of Y𝒱G.

  • Context productions: For C𝒱C,

    • ρ(X())=Y or ρ(X())=Y (and vertical analogues), where Y is a ground nonterminal and marks the hole;

    • ρ(X())=YZ() or ρ(X())=Z()Y (and all symmetric variants), where Z is a context nonterminal and Y is a ground nonterminal matching the dimensions of the hole of Z;

    • ρ(X())=Y(Z()), composition of contexts, where Y is a ground nonterminal and Z is a context nonterminal matching the dimensions of the hole of Y.

The dependency graph of nonterminals must be acyclic, guaranteeing a unique expansion Exp𝒢(X) for each nonterminal X, obtained by repeatedly applying the productions. The string derived by the whole grammar is Exp(𝒢)=Exp𝒢(𝒮), where 𝒮𝒱G is the start symbol.

The size |𝒢| is the total number of symbols in all right-hand sides, and the depth is the length of the longest path in the derivation tree. Standard 2D SLPs are exactly 2D TSLPs with 𝒱C=.

Example 17.

Consider the following small 2D SLP with holes over the alphabet Σ{0,1}. Ground nonterminals are A,B,C,T and there is one context nonterminal H(). The productions are:

  • ρ(X1)0

  • ρ(X2)1

  • ρ(X3)X1X2

  • ρ(X4())X1

  • ρ(X5())X3X4()

  • ρ(X6)X5(X1)

We have Exp(X3)=[01], Exp(X5())=[001], and finally Exp(X6)=[0001].

From Theorem 16, and noticing that Γ only contains elements of rank 2, we obtain the following (notice that standard 2D SLPs constitute a particular case of 2D SLPs with holes):

Theorem 18.

Given a 2D SLP 𝒢 with holes deriving a string TΣN×M, one can construct in time 𝒪(|𝒢|) an equivalent 2D SLP with holes of size 𝒪(|𝒢|) and depth 𝒪(log(NM)).

With Theorem 18, we can show how to obtain a random access structure that improves the bounds of De and Kempa [11] by two logarithmic factors.

Theorem 19.

Fix an arbitrary constant ϵ>0. Given a 2D SLP 𝒢 deriving a 2D string TΣN×M, one can construct in time 𝒪(|𝒢|logϵ(NM)) a data structure of size 𝒪(|𝒢|logϵ(NM)) that allows accessing any T[x][y] in 𝒪(log(NM)/loglog(NM)) time.

Proof.

We apply Theorem 18 to obtain an equivalent 2D SLP with holes of size 𝒪(|𝒢|) and depth 𝒪(log(NM)), denoted 𝒢. For every nonterminal of 𝒢 we store the size of its derived string. Additionally, for every context nonterminal of 𝒢 we store the position of its hole. Then, it is straightforward to implement random access by navigating down in the grammar from the starting nonterminal, in every step using the stored information about the size of the derived strings (and possibly the position of the hole) for every nonterminal participating in the currently considered production to decide in constant time where to continue.

Let us write 𝒢=(𝒱,𝒮,ρ). To improve the random access time, we proceed similarly as in [3, Theorem 2], namely we define new productions ρ~ as ρ~(X)=ρK(X), expanding the grammar by K=loglogϵ/3(NM) levels. Each right-hand side now has size at most logϵ/3(NM), and the depth of the grammar has decreased to 𝒪(log(NM)/loglog(NM)).

In the production rule for a nonterminal V (whether ground or context), each symbol corresponds to an axis-aligned domain, which is either a rectangle or a frame. Specifically, rectangular domains correspond to ground nonterminals (or to the hole of V, if V is a context nonterminal), while frame domains correspond to context nonterminals. Together, these domains partition the h(V)×w(V) area into b=𝒪(logϵ/3(NM)) smaller regions. We build a b×b grid by creating vertical and horizontal lines containing the sides of every rectangle (including the removed rectangle for a frame). We store the x or y coordinates for each line in a fusion tree (Lemma 1). This is illustrated in Figure 7. For each of the b2 cells, we store a pointer to the rectangle or the frame that fully contains it, and the relative position of the cell inside that rectangle or frame. Then, given a position (x,y), we first use the fusion trees to locate in constant time the cell that contains (x,y). Then, we retrieve the rectangle or the frame that contains (x,y) using the stored pointer. This gives us the ground or context nonterminal in which we should continue the descent, together with the new position (x,y). The overall size of the structure is 𝒪(|𝒢|b2)=𝒪(|𝒢|logϵ(NM)).

Figure 7: The h(V)×w(V) rectangle is partitioned into axis-aligned rectangles and frames (solid boundaries). The dashed region indicates a hole. These boundaries induce a non-uniform grid (dotted lines) with coordinates xi,yi stored in a fusion tree. A query point (x,y) (black square) falls into the grid cell defined by the intersection of the vertical and horizontal intervals [x3,x4] and [y2,y3] (light gray). These intervals are identified via predecessor queries on the fusion tree. This cell maps to a unique child nonterminal (here, the top-left frame) used for the next step of the descent.

References

  • [1] J. Adámek, J. Rosický, E. M. Vitale, and F. W. Lawvere. Algebraic Theories: A Categorical Introduction to General Algebra. Cambridge University Press, 1 edition, November 2010. doi:10.1017/CBO9780511760754.
  • [2] Amihood Amir, Gary Benson, and Martin Farach. Optimal two-dimensional compressed matching. J. Algorithms, 24(2):354–379, 1997. doi:10.1006/JAGM.1997.0860.
  • [3] Djamal Belazzougui, Patrick Hagge Cording, Simon J. Puglisi, and Yasuo Tabei. Access, rank, and select in grammar-compressed strings. In ESA, volume 9294 of Lecture Notes in Computer Science, pages 142–154. Springer, 2015. doi:10.1007/978-3-662-48350-3_13.
  • [4] Piotr Berman, Marek Karpinski, Lawrence L. Larmore, Wojciech Plandowski, and Wojciech Rytter. On the complexity of pattern matching for highly compressed two-dimensional texts. J. Comput. Syst. Sci., 65(2):332–350, 2002. doi:10.1006/JCSS.2002.1852.
  • [5] Philip Bille, Pawel Gawrychowski, Inge Li Gørtz, Gad M. Landau, and Oren Weimann. Top tree compression of tries. Algorithmica, 83(12):3602–3628, 2021. doi:10.1007/S00453-021-00869-W.
  • [6] Philip Bille, Gad M. Landau, Rajeev Raman, Kunihiko Sadakane, Srinivasa Rao Satti, and Oren Weimann. Random access to grammar-compressed strings and trees. SIAM J. Comput., 44(3):513–539, 2015. doi:10.1137/130936889.
  • [7] Nieves R. Brisaboa, Travis Gagie, Adrián Gómez-Brandón, and Gonzalo Navarro. Two-dimensional block trees. Comput. J., 67(1):391–406, 2024. doi:10.1093/COMJNL/BXAC182.
  • [8] Lorenzo Carfagna and Giovanni Manzini. The landscape of compressibility measures for two-dimensional data. IEEE Access, 12:87268–87283, 2024. doi:10.1109/ACCESS.2024.3417621.
  • [9] Lorenzo Carfagna, Giovanni Manzini, Giuseppe Romana, Marinella Sciortino, and Cristian Urbina. Generalization of repetitiveness measures for two-dimensional strings, 2025. doi:10.48550/arXiv.2505.10680.
  • [10] Moses Charikar, Eric Lehman, Ding Liu, Rina Panigrahy, Manoj Prabhakaran, Amit Sahai, and Abhi Shelat. The smallest grammar problem. IEEE Trans. Inf. Theory, 51(7):2554–2576, 2005. doi:10.1109/TIT.2005.850116.
  • [11] Rajat De and Dominik Kempa. Optimal random access and conditional lower bounds for 2D compressed strings. In SODA, 2026 (to appear).
  • [12] Michael L. Fredman and Dan E. Willard. BLASTING through the information theoretic barrier with FUSION TREES. In STOC, pages 1–7. ACM, 1990. doi:10.1145/100216.100217.
  • [13] Moses Ganardi and Pawel Gawrychowski. Pattern matching on grammar-compressed strings in linear time. In SODA, pages 2833–2846. SIAM, 2022. doi:10.1137/1.9781611977073.110.
  • [14] Moses Ganardi, Artur Jez, and Markus Lohrey. Balancing straight-line programs. J. ACM, 68(4):27:1–27:40, 2021. doi:10.1145/3457389.
  • [15] Moses Ganardi and Markus Lohrey. A Universal Tree Balancing Theorem. ACM Trans. Comput. Theory, 11:1:1–1:25, 2019. doi:10.1145/3278158.
  • [16] Dora Giammarresi and Antonio Restivo. Two-dimensional languages. In Handbook of Formal Languages (3), pages 215–267. Springer, 1997. doi:10.1007/978-3-642-59126-6_4.
  • [17] Abraham Lempel and Jacob Ziv. Compression of two-dimensional data. IEEE Trans. Inf. Theory, 32(1):2–8, 1986. doi:10.1109/TIT.1986.1057132.
  • [18] Markus Lohrey. Algorithmics on SLP-compressed strings: A survey. Groups. Complexity. Cryptology, 4(2):241–299, 2012. doi:10.1515/gcc-2012-0016.
  • [19] Oliver Matz. Regular expressions and context-free grammars for picture languages. In STACS, volume 1200 of Lecture Notes in Computer Science, pages 283–294. Springer, 1997. doi:10.1007/BFB0023466.
  • [20] Wojciech 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.
  • [21] Gift Siromoney, Rani Siromoney, and Kamala Krithivasan. Picture languages with array rewriting rules. Inf. Control., 22(5):447–470, 1973. doi:10.1016/S0019-9958(73)90573-1.
  • [22] Masaru Tomita. Parsing 2-dimensional language. In IWPT, pages 414–424. Carnegy Mellon University / ACL, 1989. URL: https://aclanthology.org/W89-0243/.
  • [23] Elad Verbin and Wei Yu. Data structure lower bounds on random access to grammar-compressed strings. In CPM, volume 7922 of Lecture Notes in Computer Science, pages 247–258. Springer, 2013. doi:10.1007/978-3-642-38905-4_24.
  • [24] Wolfgang Wechler. Universal Algebra for Computer Scientists. Springer Berlin Heidelberg, Berlin, Heidelberg, 1992. doi:10.1007/978-3-642-76771-5.

Appendix A Omitted Proofs

Lemma 9. [Restated, see original statement.]

For every N=2n, there is a 2D SLP with 𝒪(n) nonterminals deriving 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇N.

Proof.

For N=2n, let 𝖡𝗂𝗇N denote the substring of 𝖡𝗂𝗇N obtained by removing the $ symbols on the margins. We start by showing that 𝖡𝗂𝗇N can be derived with a grammar of size 𝒪(n). Since 𝖡𝗂𝗇2 has constant size, it can be derived using a constant number of nonterminals; let the starting nonterminal of the grammar be 𝒮1. We also construct nonterminals 00 and 10 that produce a single 0 and a single 1, respectively. To construct 𝖡𝗂𝗇2i+1 for i1, we inductively define nonterminals 𝒮i+1, 𝒮i+10, 𝒮i+11, 0i+1, and 1i+1 with the productions

  1. 1.

    ρ(0i+1)0i0i,

  2. 2.

    ρ(1i+1)1i1i,

  3. 3.

    ρ(𝒮i+10)0i+1𝒮i,

  4. 4.

    ρ(𝒮i+11)1i+1𝒮i,

  5. 5.

    ρ(𝒮i+1)𝒮i+10𝒮i+11,

where we inductively assume that Exp(𝒮i)=𝖡𝗂𝗇2i. It can be verified that 0i+1 (resp. 1i+1) expands to a column of 0 symbols (resp. 1 symbols) with height 2i. Then, 𝒮i+10 expands to a column of 2i zeros followed by 𝖡𝗂𝗇2i, and 𝒮i+11 expands to a column of 2i ones followed by 𝖡𝗂𝗇2i. The vertical concatenation of 𝒮i+10 and 𝒮i+11 expands to exactly 𝖡𝗂𝗇2i+1, as required. We introduce 𝒪(1) new nonterminals in order to extend the grammar of 𝖡𝗂𝗇2i to the grammar of 𝖡𝗂𝗇2i+1, so the total number of nonterminals for 𝖡𝗂𝗇2n=𝖡𝗂𝗇N is 𝒪(n). The $ symbols on the margins can be added using 𝒪(n) extra nonterminals. Hence, we can construct a grammar with 𝒪(n) nonterminals deriving 𝖡𝗂𝗇N.

We proceed to describe a 2D SLP for 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇N. Starting with 𝒮n, we inductively construct nonterminals that expand to shifted concatenations of 𝖡𝗂𝗇N. Formally, we let A0𝒮n, and for every i>0 we define Ai, Ai0, Ai1, and Zi such that:

  1. 1.

    Zi expands to a matrix of 0s with dimensions 2i1×2i1n+2,

  2. 2.

    ρ(Ai0)Ai1Zi,

  3. 3.

    ρ(Ai1)ZiAi1,

  4. 4.

    ρ(Ai)Ai0Ai1.

It can be verified by induction that Ai expands to a sequence of 2i copies of 𝖡𝗂𝗇N, each copy shifted by 1 relatively to the copy to its left. In particular, An expands to exactly 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇N. We only introduced 𝒪(n) nonterminals on top of the nonterminals 𝒮n to construct An (note that all Zi nonterminals can be constructed using additional 𝒪(n) nonterminals), so the total size of the grammar deriving 𝖲𝗁𝗂𝖿𝗍𝖡𝗂𝗇N is 𝒪(n) as required.

Appendix B Many-sorted algebras

In [14], SLPs and TSLPs are defined within the framework of many-sorted algebras, which is a general algebraic framework that allows to define SLPs and TSLPs in a very general way, independently of the actual objects considered. Informally, a many-sorted algebra is a set of typed objects and functions that respect a particular syntax, namely the rules under which objects and functions can be combined into valid expressions, depending on object types and function arities, but not on the values of such expressions. Because a SLP is defined as a set of nonterminals and productions formed by valid expressions, one relies only on the syntax to construct the derivation tree; consequently, properties such as size and depth are defined independently of the SLP’s actual evaluation in a particular algebra. In this work, we simply define many-sorted algebras as collections of sets and functions, the underlying syntax being implicit. This is enough to reformulate the first results from [14] about constructing balanced TSLPs from SLPs. For more details on this, we also refer the reader to [15], which contains the main ideas of the latter article in a simpler setting, and [1, 24] for a more general introduction to the field.

Let 𝒮 be a finite set, A=s𝒮As be a disjoint union of sets indexed by 𝒮 and Γ be a set of functions such that for every fΓ, there exist p1,,pr,q𝒮 such that f:Ap1××AprAq. In this case, we write rank(f)=r, type(f)=(p1pr,q) and sort(f)=q. Motivated by [14], we call the pair (A,Γ) a many-sorted algebra. Given a finite set 𝒱=s𝒮𝒱s of nonterminals, that is disjoint from both A and Γ, we write 𝒯γ for the set of valid expressions over 𝒱AΓ, namely if X𝒱s for some s𝒮, then X𝒯γ, and if fΓ with type(f)=(p1pr,q) and ti𝒯γ(Api𝒱pi) for every i[r], then f(t1,,tr)𝒯γ.

A straight-line program over a many-sorted algebra (A,Γ) is a tuple 𝒢=(𝒱,𝒮,ρ), such that:

  • 𝒱=s𝒮𝒱s is a finite set of nonterminals, with 𝒱Γ=.

  • 𝒮𝒱 is called the starting nonterminal.

  • ρ is a mapping from nonterminals to expressions in 𝒯γ, where for each X𝒱, one of the following holds:

    • ρ(X)=a where aAq for some q𝒮,

    • ρ(X)=f(T1,,Tr) where X𝒱q for some q𝒮, fΓ with type(f)=(p1pr,q), TiApi𝒱pi for every i[r].

    Each pair (X,ρ(X)) for X𝒱 is called a production, with X being its left-hand side and ρ(X) its right-hand side. Additionally, the relation on 𝒱 defined by XY if Y appears in the right-hand side of X must be acyclic.

From the acyclicity condition, it follows that for each nonterminal X𝒱, there is a unique element Exp𝒢(X) derived from X by recursively replacing each nonterminal in the right-hand side of its production by the corresponding derived element. The element derived by the SLP is denoted by Exp(𝒢)=Exp𝒢(𝒮). We define the size |𝒢| as the total number of symbols on the right-hand sides of all productions, and the depth of 𝒢 as the depth of its derivation tree.

Given a function fΓ with type(f)=(p1pr,q), i[r], and a1Ap1,,ai1Api1, ai+1Api+1,,arApr, we define the context f(a1,,ai1,,ai+1,,ar):ApiAq as the mapping taking bApi to f(a1,,ai1,b,ai+1,,ar).

A TSLP over a many-sorted algebra (A,Γ) is a tuple 𝒢=(𝒱,𝒮,ρ) where:

  • 𝒱=𝒱G𝒱C is a finite set of nonterminals, with 𝒱Γ=, partitioned into two disjoint sets:

    • 𝒱G=s𝒮𝒱G,s is a set of ground nonterminals.

    • 𝒱C=(p,q)𝒮2𝒱C(p,q) is a set of context nonterminals, where each X𝒱C(p,q) represents a context mapping an element of Ap to an element of Aq. In that case, we can also write X() instead of X.

  • 𝒮𝒱G is called the starting nonterminal.

  • ρ is a mapping on nonterminals, where for each X𝒱:

    • If X𝒱G,q for some q𝒮, one of the following holds:

      • *

        ρ(X)=a where aAq,

      • *

        ρ(X)=f(T1,,Tr) where fΓ with type(f)=(p1pr,q), TiApi𝒱G,pi for every i[r].

      • *

        ρ(X)=Y(T) where Y𝒱C(p,q) for some p𝒮, and TAp𝒱G,p.

    • If X𝒱C(p,q) for some p,q𝒮, one of the following holds:

      • *

        ρ(X())=f(a1,,ai1,,ai+1,,ar) where fΓ with type(f)=(p1pr,q), p=pi and ajApj for every j[r]{i}.

      • *

        ρ(X())=f(T1,,Ti1,Y(),Ti+1,,Tr) where fΓ with type(f)=(p1pr,q), Y𝒱C(p,pi), and TjApj𝒱G,pj for every j[r]{i}.

      • *

        ρ(X())=Y(Z()) where Y𝒱C(s,q) for some s𝒮, and Z𝒱C(p,s).

    As for SLPs, the relation on 𝒱 defined by XY if Y appears in the right-hand side of X must be acyclic.

We define Exp(𝒢), |𝒢| and depth(𝒢) as for SLPs. Note that, since 𝒮𝒱G, Exp(𝒢) is an element of A.

Our definition of SLPs and TSLPs requires the productions to be in a Chomsky normal form. In that sense, it differs from the one given in [14], where productions can have a right-hand side of depth more than 1, and where the depth is defined accordingly. However, it is easy to see that any general SLP or TSLP can be transformed into an equivalent one in a normal form, with equal depth and size increased only by a constant factor.

We can now formulate Theorem 16 formally:

Theorem 16 ([14, Remark 3.27]). [Restated, see original statement.]

Let (A,Γ) be a many-sorted algebra and let 𝒢 be a TSLP over (A,Γ) deriving tA. One can in time 𝒪(|𝒢|) compute an equivalent TSLP over (A,Γ) of size 𝒪(r|𝒢|), and depth 𝒪(log|t|), where r is the maximal rank of a function in Γ.

We instantiate this framework to 2D strings. Let Σ be the alphabet. The set of sorts is 𝒮=×, and for each (h,w)𝒮, A(h,w)=Σh×w. The function set Γ contains:

  • horizontal concatenation h,w1,w2:A(h,w1)×A(h,w2)A(h,w1+w2) for all h,w1,w2,

  • vertical concatenation h1,h2,w:A(h1,w)×A(h2,w)A(h1+h2,w) for all h1,h2,w.

We obtain the following result:

Theorem 18. [Restated, see original statement.]

Given a 2D SLP 𝒢 with holes deriving a string TΣN×M, one can construct in time 𝒪(|𝒢|) an equivalent 2D SLP with holes of size 𝒪(|𝒢|) and depth 𝒪(log(NM)).