Quantum Algorithm for Lexicographically Minimal String Rotation

Lexicographically minimal string rotation (LMSR) is a problem to find the minimal one among all rotations of a string in the lexicographical order, which is widely used in equality checking of graphs, polygons, automata and chemical structures. In this paper, we propose an $O(n^{3/4})$ quantum query algorithm for LMSR. In particular, the algorithm has average-case query complexity $O(\sqrt n \log n)$, which is shown to be asymptotically optimal up to a polylogarithmic factor, compared to its $\Omega\left(\sqrt{n/\log n}\right)$ lower bound. Furthermore, we show that our quantum algorithm outperforms any (classical) randomized algorithms in both worst and average cases. As an application, it is used in benzenoid identification and disjoint-cycle automata minimization.


Introduction 1.Lexicographically Minimal String Rotation
Lexicographically Minimal String Rotation (LMSR) is the problem of finding the lexicographically smallest string among all possible cyclic rotations of a given input string [Boo80].It has been widely used in equality checking of graphs [CB80], polygons [IS89,Mae91], automata [Pup10] (and their minimizations [AZ08]) and chemical structures [Shi79], and in generating de Bruijn sequences [SWW16,DHS + 18] (see also [GY03,vLWW01]).Booth [Boo80] first proposed an algorithm in linear time for LMSR based on the Knuth-Morris-Pratt string-matching algorithm [KMP77].Shiloach [Shi81] later improved Booth's algorithm in terms of performance.A more efficient algorithm was developed by Duval [Duv83] from a different point of view known as Lyndon Factorization.All these algorithms for LMSR are deterministic and have worst-case time complexity Θ(n).After that, several parallel algorithms for LMSR were developed.Apostolico, Iliopoulos and Paige [AIP87] found an O(log n) time CRCW PRAM (Concurrent Read Concurrent Write Parallel Random-Access Machine) algorithm for LMSR using O(n) processors, which was then improved by Iliopoulos and Smyth [IS92] to use only O(n/ log n) processors.
The LMSR of a string s can also be computed by finding the lexicographically minimal suffix of ss$, i.e. the concatenation of two occurrences of s and an end-marker $, where $ is considered as a character lexicographically larger than every character in s.The minimal suffix of a string can be found in linear time with the help of data structures known as suffix trees [Wei73, AHU74,McC76] and suffix arrays [MM90, GBYS92,KSB06], and alternatively by some specific algorithms [Duv83,Cro92,Ryt03] based on Duval's algorithm [Duv83] or the KMP algorithm [KMP77].

Quantum Algorithms for String Problems
Although a large number of new quantum algorithms have been found for various problems (e.g., [Sho94, Gro96, B Š06, Amb07, MSS07, HHL09, BS17]), only a few of them solve string problems.
Pattern matching is a fundamental problem in stringology, where we are tasked with determining whether a pattern P of length m occurs in a text T of length n.In classical computing, it is considered to be closely related to LMSR.The Knuth-Morris-Pratt algorithm [KMP77] used in Booth's algorithm [Boo80] for LMSR mentioned above is one of the first few algorithms for pattern matching, with time complexity Θ(n + m).Recently, several quantum algorithms have been developed for pattern matching; for example, Ramesh and Vinay [RV03] developed an O √ n log(n/m) log m + √ m log 2 m quantum pattern matching algorithm based on a useful technique for parallel pattern matching, namely deterministic sampling [Vis90], and Montanaro [Mon17] proposed an average-case O (n/m) d 2 O(d 3/2 √ log m) quantum algorithm for d-dimensional pattern matching.However, it seems that these quantum algorithms for pattern matching cannot be directly generalized to solve LMSR.Additionally, quantum algorithms for reconstructing unknown strings with nonstandard queries have been proposed; for example, substring queries [CILG + 12] and wildcard queries [AM14].Recently, a quantum algorithm that approximates the edit distance within a constant factor was developed in [BEG + 18].Soon after, Le Gall and Seddighin [LGS22] studied quantum algorithms for several other string problems: longest common substring, longest palindrome substring, and Ulam distance.

Main Contributions of This Paper
A naive quantum algorithm for LMSR (see Definition 2.1 for its formal definition) is to find the LMSR of the string within O( √ n) comparisons of rotations by quantum minimum finding [DH96,AK99] among all rotations.However, each comparison of two rotations in the lexicographical order costs O( √ n) and is bounded-error.Combining the both, an Õ(n) quantum algorithm for LMSR is obtained, which has no advantages compared to classical algorithms.In this paper, however, we find a more efficient quantum algorithm for LMSR.Formally, we have: Theorem 1.1 (Quantum Algorithm for LMSR).There is a bounded-error quantum query algorithm for LMSR, for which the worst-case query complexity is O n 3/4 and average-case query complexity is O ( √ n log n).
In the top-level design of this algorithm, we are required to find the minimal value of a function, which is given by a bounded-error quantum oracle.To resolve this issue, we develop an efficient error reduction for nested quantum algorithms (see Section 1.4.1 for an outline).With this framework of nested quantum algorithms, we are able to solve problems in nested structures efficiently.The high level illustrations of the algorithm for the worst and average cases are given in Section 1.4.2 and Section 1.4.3,respectively.A detailed description of the algorithm is presented in Section 5.
We assume access to a quantum-read/classical-write random access memory (QRAM) and define time complexity as the number of elementary two-qubit quantum gates, input queries and QRAM operations (see Section 2.2.2 for more details).Our quantum algorithm uses only O(log 2 n) classical bits in QRAM and O(log n) "actual" qubits in the quantum computation.Thus, the time complexity of our quantum algorithms in this paper is just an O(log n) factor bigger than their query complexity (in both worst and average cases).
In order to show a separation between classical and quantum algorithms for LMSR, we settle the classical and quantum lower bounds for LMSR in both the worst and average cases.Let R(LMSR) and R unif (LMSR) be the worst-case and average-case (classical) randomized query complexities for LMSR, and let Q(LMSR) and Q unif (LMSR) be their quantum counterparts.Then we have: Theorem 1.2 (Classical and Quantum Lower Bounds for LMSR).
2. For every bounded-error quantum algorithm for LMSR, it has worst-case query complexity Ω ( √ n) and average-case query complexity Ω n/ log n .That is, Q(LMSR) = Ω( √ n) and Remark 1.1.It suffices to consider only bounded-error quantum algorithms for LMSR, as we can show that every exact (resp.zero-error) quantum algorithm for LMSR has worst-case query complexity Ω(n).This is achieved by reducing the search problem to LMSR (see Appendix F), since the search problem is known to have worst-case query complexity Ω(n) for exact and zero-error quantum algorithms [BBC + 01].
Theorem 1.2 is proved in Section 6.Our main proof technique is to reduce a total Boolean function to LMSR and to find a lower bound of that Boolean function based on the notion of block sensitivity.The key observation is that the block sensitivity of that Boolean function is related to the string sensitivity of input (Lemma 6.3, and see Section 1.4.3 for more discussions).The results of Theorems 1.1 and 1.2 can be summarized as Table 1.
Therefore, our quantum algorithm is asymptotically optimal in the average case up to a logarithmic factor.Moreover, a quantum separation from (classical) randomized computation in both the worstcase and average-case query complexities is achieved: 1. Worst case: Q(LMSR) = O n 3/4 but R(LMSR) = Ω(n); and 2. Average case: In other words, our quantum algorithm is faster than any classical randomized algorithms both in the worst case and the average case.
As an application, we show that our algorithm can be used in identifying benzenoids [Baš16] and minimizing disjoint-cycle automata [AZ08] (see Section 7).The quantum speedups for these problems are illustrated in Table 2.

Classical
Quantum (this work Recent Developments.After the work described in this paper, the worst-case quantum query complexity of LMSR was further improved to n 1/2+o(1) in [AJ22] by refining the exclusion rule of LMSR proposed in this paper (see Lemma 4.8 of [AJ22]), and later a quasi-polylogarithmic improvement was achieved in [Wan22].A quantum algorithm for the decision version of LMSR with worst-case query complexity Õ( √ n) was proposed in [CKKD + 22] under their quantum divideand-conquer framework.
As an application, the near-optimal quantum algorithm for LMSR [AJ22] was then used as a subroutine in finding the longest common substring of two input strings [JN23].

Overview of the Technical Ideas
Our results presented in the above subsection are achieved by introducing the following three new ideas:

Optimal Error Reduction for Nested Quantum Minimum Finding
Our main algorithm for LMSR is essentially a nest of quantum search and minimum finding.A major difficulty in its design is error reduction in nested quantum oracles, which has not been considered in the previous studies of nested quantum algorithms (e.g., nested quantum search analyzed by Cerf, Grover and Williams [CGW00] and nested quantum walks introduced by Jeffery, Kothari and Magniez [JKM13]).
A d-level nested classical algorithm needs O(log d−1 n) repetitions to ensure a constant error probability by majority voting.For a d-level quantum algorithm composed of quantum minimum finding, it is known that only a small factor O(log n) of repetitions is required [CGYM08].We show that this factor can be even better; that is, only O(1) of repetitions are required as if there were no errors in quantum oracles: • We extend quantum minimum finding algorithm [DH96,AK99] to the situation where the input is given by a bounded-error oracle so that it has query complexity O( √ n) (see Lemma 3.4) rather than O( √ n log n) straightforwardly by majority voting.
• We introduce a success probability amplification method for quantum minimum finding on bounded-error oracles, which requires O n log(1/ε) query complexity to obtain the minimum with error probability ≤ ε (see Lemma 3.5).In contrast, a straightforward solution by O(log(1/ε)) repetitions of the O( √ n) algorithm (by Lemma 3.4) has query complexity These ideas are inspired by quantum searching on bounded-error oracles [HMdW03] and amplification of success of quantum search [BCdWZ99].The above two algorithms will be used in the main algorithm for LMSR as a subroutine.Both of them are optimal because their simpler version (OR function) has lower bound Ω( √ n) [BBBV97,BBHT98,Zal99] for quantum bounded-error algorithm and Ω( n log(1/ε)) [BCdWZ99] for its error reduction.To be clearer, we compare the results about quantum searching and quantum minimum finding in the previous literature and ours in Table 3.

Algorithm type Oracle type
Table 4: Quantum query complexities improved by our nested quantum algorithm framework.

Exclusion Rule of LMSR
We find a useful property of LMSR, named exclusion rule (Lemma 5.1): for any two overlapped substrings which are prefixes of the canonical representation of a string, the LMSR of the string cannot be the latter one.This property enables us to reduce the worst-case query complexity by splitting the string into blocks of suitable sizes, and in each block the exclusion rule can apply so that there is at most one candidate for LMSR.This kind of trick has been used in parallel algorithms, e.g., Lemma 1.1 of [IS92] and the Ricochet Property of [Vis90].However, the exclusion rule of LMSR used here is not found in the literature (to the best of our knowledge).We outline our algorithm as follows: 1 Let B = ⌊ √ n⌋ and L = ⌊B/4⌋.We split s into ⌈n/L⌉ blocks of size L (except the last block).
2 Find the prefix p of SCR(s) of length B, where SCR(s) is the canonical representation of s.
3 In each block, find the leftmost index that matches p as the candidate.Only the leftmost index is required because of the exclusion rule of LMSR.
4 Find the lexicographically minimal one among all candidates in blocks.In case of a tie, the minimal candidate is required.
A formal description and the analysis of this algorithm is given in Section 5.1.In order to find the leftmost index that matches p (Step 3 of this algorithm) efficiently, we adopt the deterministic sampling [Vis90] trick.That is, we preprocess a deterministic sample of p, with which whether an index matches p can be checked within O(log|p|) rather than O(|p|) comparisons.Especially, we allow p to be periodic, and therefore extend the definition of deterministic samples for periodic strings (see Definition 4.1) and propose a quantum algorithm for finding a deterministic sample of a string (either periodic or aperiodic) (see Algorithm 4).

String Sensitivity
We also observe the property of LMSR that almost all strings are of low string sensitivity (Lemma 5.3), which can be used to reduce the query complexity of our quantum algorithm significantly in the average case.Here, the string sensitivity of a string (see Definition 5.1) is a metric showing the difficulty to distinguish its substrings, and helpful to obtain lower bounds for LMSR (see Lemma 6.3).We outline our improvements for better average-case query complexity as follows: 1 Let s 1 and s 2 be the minimal and the second minimal substrings of s of length B = O(log n), respectively.
2 If s 1 < s 2 lexicographically, then return the starting index of s 1 ; otherwise, run the basic quantum algorithm given in Section 1.4.2.
Intuitively, in the average case, we only need to consider the first O(log n) characters in order to compare two rotations.The correctness is straightforward but the average-case query complexity needs some analysis.See Section 5.2 for a formal description and the analysis of the improvements.

Organization of This Paper
We recall some basic definitions about strings and quantum query algorithms, and formally define the LMSR problem in Section 2. An efficient error reduction for nested quantum algorithms is developed in Section 3.An improved quantum algorithm for pattern matching based on the new error reduction technique (given in Section 3) is proposed in Section 4. The quantum algorithm for LMSR is proposed in Section 5.The classical and quantum lower bounds for LMSR are given in Section 6.The applications are discussed in Section 7.

Preliminaries
For convenience of the reader, in this section, we briefly review the lexicographically minimal string rotation (LMSR) problem, quantum query model and several notions of worst-case and average-case complexities used in the paper.The period of a string s ∈ Σ n is the minimal positive integer d such that s[i] = s[i + d] for every 0 ≤ i < n − d.String s is called periodic if its period ≤ n/2, and s is aperiodic if it is not periodic.

Lexicographically Minimal String Rotation
Let s ∈ Σ n and t ∈ Σ m .The concatenation of s and t is string . We say that s is smaller than t in the lexicographical order, denoted s < t, if either s is a prefix of t but s = t, or there exists an index 0 ≤ k < min{n, m} such that s Definition 2.1 (Lexicographically Minimal String Rotation).For any string s ∈ Σ n of length n, we call s (k) = s[k . . .k + n − 1] the rotation of s by offset k.The lexicographically minimal string rotation (LMSR) problem is to find an offset k such that s (k) is the minimal string among s (0) , s (1) , . . ., s (n−1) in the lexicographical order.The minimal s (k) is called the string canonical representation (SCR) of s, denoted SCR(s); that is, SCR(s) = min s (0) , s (1) , . . ., s (n−1) .
In case of a tie; that is, there are multiple offsets such that each of their corresponding strings equals to SCR(s), then the minimal offset is desired, and the goal is to find The LMSR problem has been well-studied in the literature [CB80, Boo80, Shi81, Duv83, Jeu93, CR94,CHL07], and several linear time (classical) algorithms for LMSR are known, namely Booth's, Shiloach's and Duval's Algorithms: Theorem 2.1 ( [Boo80, Shi81, Duv83]).There is an O(n) deterministic algorithm for LMSR.

Quantum Query Algorithms
Our computational model is the quantum query model [Amb04,BdW02].The goal is to compute an n-variable function f (x) = f (x 0 , x 1 , . . ., x n−1 ), where x 0 , x 1 , . . ., x n−1 are input variables.For example, the LMSR problem can be viewed as function f (x) = LMSR(x 0 , x 1 , . . .x n−1 ), where x 0 x 1 x 2 . . .x n−1 denotes the string of element x 0 , x 1 , . . ., x n−1 .The input variables x i can be accessed by queries to a quantum oracle O x (which is a quantum unitary operator) defined by O x |i, j = |i, j ⊕ x i , where ⊕ is the bitwise exclusive-OR operation.A quantum algorithm A with T queries is described by a sequence of quantum unitary operators The intermediate operators U 0 , U 1 , . . ., U T can be arbitrary quantum unitary operators that are determined independent of O x .The computation is performed in a Hilbert space H = H o ⊗ H w , where H o is the output space and H w is the work space.The computation starts from basis state |0 o |0 w , and then we apply U 0 , O x , U 1 , O x , . . ., O x , U T on it in that order.The result state is Measuring the output space, the outcome is then defined as the output A(x) of algorithm A on input x.More precisely, Pr[A(x) = y] = M y |ψ 2 , where M y = |y o y|.Furthermore, A is said to be a bounded-error quantum algorithm that computes f , if Pr[A(x) = f (x)] ≥ 2/3 for every x.
To deal with average-case complexity, following the setting used in [AdW99], we assume that after each U j , a dedicated flag-qubit will be measured on the computational basis (and this measurement may change the quantum state).The measurement outcome indicates whether the algorithm is ready to halt and return its output.If the outcome is 1, then we measure the output space with the outcome as the output, and then stop the algorithm; otherwise, the algorithm continues with the next query O x and U j+1 .Let T A (x) denote the expected number of queries that A uses on input x.Note that T A (x) only depends on the algorithm A and its given input x (which is fixed rather than from some distribution).

Worst-Case and Average-Case Query Complexities
Let f : {0, 1} n → {0, 1} be a Boolean function.If A is a (either randomized or quantum) algorithm and y ∈ {0, 1}, we use Pr[A(x) = y] to denote the probability that A outputs y on input x.Let R(f ) and Q(f ) be the set of randomized and quantum bounded-error algorithms that compute f , respectively: Then the worst-case query complexities of f are: Let µ : {0, 1} n → [0, 1] be a probability distribution.We usually use unif ≡ 2 −n to denote the uniform distribution.The average-case query complexity of an algorithm A with respect to µ is Thus, the randomized and quantum average-case query complexities of f with respect to µ are: Clearly, Q µ (f ) ≤ R µ (f ) for all f and µ.

Time and Space Efficiency
In order to talk about the "time" and "space" complexities of quantum algorithms, we assume access to a quantum-read/classical-write random access memory (QRAM), where it takes a single QRAM operation to either classically write a bit to the QRAM or make a quantum query to a bit stored in the QRAM.For simplicity, we assume the access to the QRAM is described by a quantum unitary operator U QRAM that swaps the accumulator and a register indexed by another register: where r 0 , r 1 , . . ., r M −1 are bit registers that are only accessible through this QRAM operator.
Let A be a quantum query algorithm, and t A (x) denote the expected number of two-qubit quantum gates and QRAM operators U QRAM composing intermediate operators, and the quantum input oracles O x that A uses on input x.The space complexity of A measures the number of (qu)bits used in A. The worst-case and average-case time complexities of a Boolean function f are defined similarly to Section 2.2.1 by replacing T A (x) with t A (x).

Optimal Error Reduction for Nested Quantum Algorithms
Our quantum algorithm for LMSR (Theorem 1.1) is essentially a nested algorithm calling quantum search and quantum minimum finding.The error reduction is often crucial for nested quantum algorithms.Traditional probability amplification methods for randomized algorithms can obtain an O log d n slowdown for d-level nested quantum algorithms by repeating the algorithm O(log n) times in each level.In this section, we introduce an efficient error reduction for nested quantum algorithms composed of quantum search and quantum minimum finding, which only costs a factor of O(1).This improvement is obtained by finding an O ( √ n) quantum algorithm for minimum finding when the comparison oracle can have bounded errors (see Algorithm 1).Moreover, we also show how to amplify the success probability of quantum minimum finding with both exact and bounded-error oracles.In particular, we obtain an O n log (1/ε) quantum algorithm for minimum finding with success probability ≥ 1− ε (see Algorithm 2).These two algorithms allow us to control the error produced by nested quantum oracles better than traditional (classical) methods.Both of them are optimal because their simpler version (OR function) has lower bound Ω( √ n) [BBBV97, BBHT98, Zal99] for quantum bounded-error algorithm and Ω( n log(1/ε)) [BCdWZ99] for its error reduction.As an application, we develop a useful tool to find the first solution in the search problem.

Quantum Search
Let us start from an O ( √ n) quantum algorithm to search on bounded-error inputs [HMdW03].
The search problem is described by a function f (x 0 , x 1 , . . ., x n−1 ) that finds an index j ∈ [n] (if exists) such that x j = 1, where x i ∈ {0, 1} for all i ∈ [n].It was first shown by Grover [Gro96] that the search problem can be solved by an O ( √ n) quantum algorithm, which was found after the discovery of the Ω( √ n) lower bound [BBBV97] (see also [BBHT98,Zal99]).

Quantum Search on Bounded-Error Oracles
A more robust approach for the search problem on bounded-error oracles was proposed by Høyer, Mosca and de Wolf [HMdW03].Rather than an exact quantum oracle U x |i, 0 = |i, x i , they consider a bounded-error one introducing extra workspace |0 w : where p i ≥ 2/3 for every i ∈ [n], ū denotes the negation of u, and |ψ i w and |φ i w are ignorable work qubits.This kind of bounded-error oracles is general in the sense that every bounded-error quantum algorithm and (classical) randomized algorithm can be described by it.A naive way to solve the search problem on bounded-error oracles is to repeat k = O(log n) times and choose the majority value among the k outputs.This gives an O ( √ n log n) quantum algorithm.Surprisingly, it can be made better to O ( √ n) as shown in the following: bounded-error quantum algorithm for the search problem on bounded-error oracles.Moreover, if there are t ≥ 1 solutions, the algorithm finds a solution in expected O n/t queries (even if t is unknown).
For convenience, we use Search(U x ) to denote the algorithm of Theorem 3.1 which, with probability ≥ 2/3, returns an index j ∈ [n] such that x j = 1 or reports that no such j exists (we require the algorithm to return −1 in this case).

Amplification of the Success of Quantum Search
Usually, we need to amplify the success probability of a quantum or (classical) randomized algorithm to make it sufficiently large.A common trick used in randomized algorithms is to repeat the bounded-error algorithm O(log(1/ε)) times and choose the majority value among all outputs to ensure success probability ≥ 1 − ε.Buhrman, Cleve, de Wolf and Zalka [BCdWZ99] showed that we can do better for quantum searching.
Theorem 3.2 (Amplification of the success of quantum search, [BCdWZ99]).For every ε > 0, there is an O n log(1/ε) bounded-error quantum algorithm for the search problem with success probability ≥ 1 − ε.Moreover, if there is a promise of t ≥ 1 solutions, the algorithm finds a solution in O Theorem 3.2 also holds for bounded-error oracles.For convenience, we use Search(U x , ε) to denote the algorithm of Theorem 3.2, which succeeds with probability ≥ 1 − ε.Note that Theorem 3.2 does not cover the case that there can be t ≥ 2 solutions without promise.In this case, we can obtain an O n/t log(1/ε) bounded-error quantum algorithm with error probability ≤ ε by straightforward majority voting.

Quantum Minimum Finding
We now turn to consider the minimum-finding problem.Given x 0 , x 1 , . . ., x n−1 , the problem is to find an index j ∈ [n] such that x j is the minimal element.Let cmp(i, j) be the comparator to determine whether x i < x j : The comparison oracle U cmp simulating cmp is defined by We measure the query complexity by counting the number of queries to this oracle U cmp .A quantum algorithm was proposed by Dürr and Høyer [DH96] and Ahuja and Kapoor [AK99] for finding the minimum: There is an O ( √ n) bounded-error quantum algorithm for the minimum-finding problem.
We also note that a generalized minimum-finding was developed in [vAGGdW17], which only needs to prepare a superposition over the search space (rather than make queries to individual elements of the search space).

Optimal Quantum Minimum Finding on Bounded-Error Oracles
For the purpose of this paper, we need to generalize the above algorithm to one with a bounded-error version of U cmp .For simplicity, we abuse a little bit of notation and define: where p ij ≥ 2/3 for all i, j ∈ [n], and |ψ ij w and |φ ij w are ignorable work qubits.Moreover, for every index j ∈ [n], we can obtain a bounded-error oracle U j cmp : with only one query to U cmp .Then we can provide a quantum algorithm for minimum finding on bounded-error oracles as Algorithm 1.
The constant C > 0 in Algorithm 1 is given so that Search(U x ) in Theorem 3.1 takes at most C n/ max{t, 1} queries to U x if there are t solutions.
Lemma 3.4.Algorithm 1 is a bounded-error quantum algorithm for minimum finding on boundederror oracles in O ( √ n) queries.
Proof.The query complexity is trivially O( √ n) due to the guard (Line 7) of Algorithm 1.
The correctness is proved as follows.Let m = ⌈12 ln n⌉ and q = ⌈36 ln m⌉.We assume that n ≥ 3 and therefore m ≥ 12.In each of the m iterations, Line 11-14 of Algorithm 1 calls U cmp for q times and b gets the value (i = −1) ∧ (x i < x j ) with probability ≥ 1 − 1/m 2 (This is a straightforward majority voting.For completeness, its analysis is provided in Appendix A).Here, i is an index such that x i < x j (with high probability) and i = −1 if no such i exists; thus b = 1 means that there exists smaller element x i than x j .
We only consider the case that the values of b in all iterations are as desired.This case happens with probability ≥ (1 − 1/m 2 ) m ≥ 1 − 1/m ≥ 11/12.In each iteration, i finds a candidate index Algorithm 1 Minimum(U cmp ): An algorithm for minimum finding on bounded-error oracles.
return the answer by classical algorithms.
if the total number of queries to U cmp > 30C √ n + mq then 8: break.

9:
end if , where U j cmp is defined by Eq. (1). 11: b k ← the measurement outcome of the third register of U cmp |i, j, 0 |0 w .
with probability ≥ 2/3 such that x i < x j if exists (and if there are many, any of them is obtained with equal probability).It is shown in [DH96, Lemma 2] that: if i finds a candidate index with certainty, then the expected number of queries before j holds the index of the minimal is ≤ 5 2 C √ n; moreover, the expected number of iterations is ≤ ln n.In our case, i finds a candidate index in expected 3/2 iterations.Therefore, the expected number of queries to U cmp is ≤ 15 4 C √ n and that of iterations is ≤ 3 2 ln n.When Algorithm 1 makes queries to the oracle ≥ 30C √ n times (except those negligible queries in Line 11-14) or iterations ≥ m times (that is, more than 8 times their expectations), the error probability is ≤ 1/8 + 1/8 = 1/4 by Markov's inequality.Therefore, the overall success probability is ≥ 11 12 • 3 4 ≥ 2/3.

Amplifying the Success Probability of Quantum Minimum Finding
We can amplify the success probability for quantum minimum finding better than a naive method, as shown in Algorithm 2.
Proof.Algorithm 2 terminates with a guard by Search(U j cmp , ε).Here, Search(U j cmp , ε) = −1 means that with probability ≥ 1 − ε, there is no index i such that cmp(i, j) = 1 and thus j is the desired answer.Therefore, it has error probability ≤ ε as the guard.Let p ≥ 2/3 be the probability that j holds the index of the minimal element with a single query to Minimum(U cmp ) by Lemma 3.4.Let q be the probability that Algorithm 2 breaks the "while" loop at each iteration.Then Algorithm 2 Minimum(U cmp , ε): Amplification of the success of minimum finding.Input: A bounded-error oracle U cmp for x 0 , x 1 , . . ., x n−1 and 0 < ε < 1/2.Output: An index j ∈ [n] such that x j ≤ x i for every i ∈ [n] with probability ≥ 1 − ε. 1: while true do break.
which is greater than a constant.So, the expected number of iterations is O(1).In a single iteration, Minimum(U cmp ) takes O ( √ n) queries (by Lemma 3.4) and Search(U j cmp , ε) takes O n log(1/ε) queries (by Theorem 3.2).Therefore, the expected query complexity of Algo-

An Application: Searching for the First Solution
In this subsection, we develop a tool needed in our quantum algorithm for LMSR as an application of the above two subsections.It solves the problem of finding the first solution (i.e.leftmost solution, or solution with the minimal index rather than an arbitrary solution) and thus can be seen as a generalization of quantum searching, but the solution is based on quantum minimum finding.Formally, the query oracle U x of x 0 , x 1 , . . ., x n−1 is given.The searching-first problem is to find the minimal index j ∈ [n] such that x j = 1 or report that no solution exists.This problem can be solved by minimum-finding with the comparator In the case that the query oracle U x is bounded-error, a bounded-error comparison oracle U cmp corresponding to cmp can be implemented with a constant number of queries to U x .Therefore, the results in Lemma 3.4 and Lemma 3.5 also hold for the searching-first problem.For convenience in the following discussions, we write SearchFirst(U x ) and SearchFirst(U x , ε) to denote the algorithm for the searching-first problem based on the two algorithm Minimum(U cmp ) and Minimum(U cmp , ε), respectively.Symmetrically, we have SearchLast(U x ) and SearchLast(U x , ε) for searching the last solution.
Recently, an O( √ n) quantum algorithm for searching the first was proposed in [KKM + 20].
Their approach is quite different from our presented above.It is specifically designed for this particular problem, but our approach is based on a more general framework of quantum minimum finding.
We believe that the techniques presented in this section can be applied in solving other problems.For this reason, we present a description of them in a general framework of nested quantum algorithm in Appendix B.

Quantum Deterministic Sampling
In this section, we prepare another tool to be used in our quantum algorithm for LMSR, namely an efficient quantum algorithm for deterministic sampling.It is based on our nested quantum algorithm composed of quantum search and quantum minimum finding given in the last section.Deterministic sampling is also a useful trick in parallel pattern matching [Vis90].We provide a simple quantum lexicographical comparator in Section 4.1, and a quantum algorithm for deterministic sampling in Section 4.2.As an application, we obtain quantum algorithms for string periodicity and pattern matching in Section 4.3.

Lexicographical Comparator
Suppose there are two strings s, t ∈ Σ n of length n over a finite alphabet Σ = [α].Let U s and U t be their query oracles, respectively.That is, In order to compare the two strings in the lexicographical order, we need to find the leftmost index If no such k exists, then s = t.To this end, we construct the oracle Remark 4.1.We usually need to compare two strings in the lexicographical order as a subroutine nested as low-level quantum oracles in string algorithms.However, the lexicographical comparator (Algorithm 3) brings errors.Therefore, the error reduction trick for nested quantum oracles proposed in Section 3 is required here.

Deterministic Sampling
Deterministic sampling [Vis90] is a useful technique for pattern matching in pattern analysis.In this subsection, we provide a quantum solution to deterministic sampling in the form of a nested quantum algorithm.
For our purpose, we extend the definition of deterministic samples to the periodic case.The following is a generalised definition of deterministic samples.Definition 4.1 (Deterministic samples).Let s ∈ Σ n and d be its period.A deterministic sample of s consists of an offset 0 ≤ δ < ⌊n/2⌋ and a sequence of indices i 0 , i 1 , . . ., i l−1 (called checkpoints) such that when the exact values of i k and δ are ignorable.
If s is aperiodic (i.e.d > n/2), the second condition degenerates into "for every 0 ≤ j < ⌊n/2⌋ with j = δ", which is consistent with the definition for aperiodic strings in [Vis90].
The use of deterministic sampling.Suppose that T is a text and P is a pattern.If we have a deterministic sample (δ; i 0 , i 1 , . . ., i l−1 ) of P with a small l, then we can test if an index of T can be a starting position that matches P using only l comparisons according to the deterministic sample.It is worth noting that one can disqualify two possible starting positions (that pass the above testing of deterministic sampling) by the Ricochet property proposed in [Vis90] (see Lemma D.1).
The following theorem shows that the size of the deterministic sample can be every small.
Proof.For the case that s is aperiodic, a simple procedure for constructing a valid deterministic sample was given in [Vis90].We describe it as follows.
1. Initially, let A 0 = [⌊n/2⌋] be the set of candidates of δ, and S 0 = ∅ be the set of checkpoints.2.2.Otherwise, there must be an index ] (or s is periodic).Let σ k be the symbol with least occurrences (but at least once) among s[i k −γ] for γ ∈ A k (and choose any of them if there are multiple possible symbols).Let It can be seen that the above procedure always stops as the set A k halves after each step, i.e., |A k+1 | ≤ |A k |/2.It can be verified that the returned δ and checkpoints together form a valid deterministic sample.The procedure will have at most ⌊log 2 n⌋ steps and each step will add one checkpoint, which implies that there exist a deterministic sample with at most ⌊log 2 n⌋ checkpoints.
For the case that s is periodic, the above procedure will still work if we set the initial set of candidates to be A 0 = [d].Intuitively, since s is periodic, most symbols are redundant and thus we only have to consider the first d offsets.After this modification, the analysis of the modified procedure is almost identical to the original one.Here, we note that if i k does not exist during the execution of the modified procedure, then s has a smaller period than d.Finally, the procedure will return at most ⌊log 2 d⌋ ≤ ⌊log 2 n⌋ checkpoints.Now let us consider how a quantum algorithm can do deterministic sampling.We start from the case where s ∈ Σ n is aperiodic.Let U s be the query oracle of s, that is, U |i, j = |i, j ⊕ s[i] .Suppose at step l, the sequence of indices i 0 , i 1 , . . ., i l−1 is known as well as (we need not know δ explicitly).For 0 ≤ j < ⌊n/2⌋, let x j denote whether candidate j agrees with δ at all checkpoints, that is, Based on the search problem, there is a bounded-error oracle U x for computing A quantum algorithm for deterministic sampling is described in Algorithm 4. Initially, all offsets 0 ≤ ξ < ⌊n/2⌋ are candidates of δ.The idea of the algorithm is to repeatedly find two remaining candidates p and q that differ at an index j (if there is only one remaining candidate, the algorithm has already found a deterministic sample and terminates), randomly choose a character c being s[j − p] or s[j − q], and delete either p or q according to c.It is sufficient to select p and q to be the first and the last solution of x j defined in Eq. (3).To explicitly describe how to find an index j where p and q differ, we note that q ≤ j < p + n and j must exist because of the aperiodicity of s, and let It is trivial that there is an exact oracle U y for computing y j with O(1) queries to U s .
For the case of periodic s ∈ Σ n , the algorithm requires some careful modifications.We need a variable Q to denote the upper bound of current available candidates.Initially, Q = ⌊n/2⌋ − 1.We modify the definition of x j in Eq. (3) to make sure 0 ≤ j ≤ Q by For an aperiodic string s, there is at least one y j such that y j = 1, so the algorithm will reach Line 17-25 during its execution with small probability ≤ 1/m, where m = O(log n).But for periodic string s, let d be its period, if q − p is divisible by d, then y j = 0 for all y j and thus the algorithm once reaches Line 17-25 with high probability ≥ 1 − 1/6m 2 .In this case, there does not exist q ≤ j < p + n such that y j = 1.We set Q = q − 1 to eliminate all candidates ≥ q.In fact, even for a periodic string s, the algorithm is intended to reach Line 17-25 only once (with high probability).If the algorithm reaches Line 17-25 the second (or more) time, it is clear that current (δ; i 0 , i 1 , . . ., i l−1 ) is a deterministic sample of s (with high probability ≥ 1 − 1/m), and therefore consequent computation does not influence the correctness and can be ignored.
Lemma 4.3.Algorithm 4 is an O n log 3 n log log n bounded-error quantum algorithm for deterministic sampling.
Let U x be the bounded-error oracle for computing x j defined in Eq. (4).

28:
l ← l + 1. 29: end for 30: Let U x be the bounded-error oracle for computing x j defined in Eq. (3).31: δ ← SearchFirst(U x , ε). 32: return (δ; i 0 , i 1 , . . ., i l−1 ).bring errors.It is clear that each call to Search, SearchFirst or SearchLast has error probability ≤ ε.Therefore, Algorithm 4 runs with no errors from Search, SearchFirst or SearchLast with probability ≥ (1 − ε) 6m ≥ 1 − 1/m.Now suppose Algorithm 4 runs with no errors from Search, SearchFirst or SearchLast.To prove the correctness of Algorithm 4, we consider the following two cases: 1. Case 1. s is aperiodic.In this case, Algorithm 4 will never reach Line 17-25.In each iteration, the leftmost and the rightmost remaining candidates p and q are found.If p = q, then only one candidate remains, and thus a deterministic sample is found.If p = q, then there exists an index q ≤ j < p + n such that s[j − p] and s[j − q] differ.We set i l = j and set c l randomly from s[j − p] and s[j − q] with equal probability.Then with probability 1/2, half of the remaining candidates are eliminated.In other words, it is expected to find a deterministic sample in 2 log 2 n iterations.The iteration limit to m ≥ 8 log 2 n will make error probability ≤ 1/4.That is, a deterministic sample is found with probability ≥ 3/4.
2. Case 2. s is periodic and the period of s is d ≤ n/2.In each iteration, the same argument for aperiodic s holds if Algorithm 4 does not reach Line 17-25.If Line 17-25 is reached for the first time, it means candidates between q + 1 and ⌊n/2⌋ − 1 are eliminated and q − p is divisible by d.If Line 17-25 is reached for the second time, all candidates p ≡ q (mod d) are eliminated, and therefore a deterministic sample is found.
Combining the above two cases, a deterministic sample is found with probability ≥ 3/4(1 − 1/m) ≥ 2/3.On the other hand, we note that a single call to SearchFirst and SearchLast in Algorithm Remark 4.2.In order to make our quantum algorithm for deterministic sampling time and space efficient, we need to store and modify the current deterministic sample (δ; i 0 , i 1 , . . ., i l−1 ) during the execution in the QRAM, which needs O(l log n) = O(log 2 n) bits of memory.Moreover, only O(log n) qubits are needed in the computation (for search and minimum finding).In this way, the time complexity of the quantum algorithm is O n log 5 n log log n , which is just an O(log n) factor bigger than its query complexity.

Applications
Based on our quantum algorithm for deterministic sampling, we provide applications for string periodicity and pattern matching.

String Periodicity
We can check whether a string is periodic (and if yes, find its period) with its deterministic sample.Formally, let (δ; i 0 , i 1 , . . ., i l−1 ) be a deterministic sample of s, and x j defined in Eq. (3).Let j 1 denote the smallest index j such that x j = 1, which can be computed by SearchFirst on x j .After j 1 is obtained, define Let j 2 denote the smallest index j such that x ′ j = 1 (if not found then j 2 = −1), which can be computed by SearchFirst on x ′ j .If j 2 = −1, then s is aperiodic; otherwise, s is periodic with period d = j 2 − j 1 .This algorithm for checking periodicity is O √ n log n .(See Appendix D for more details.)

Pattern Matching
As an application of deterministic sampling, we have a quantum algorithm for pattern matching with query complexity O √ n log m + m log 3 m log log m , better than the best known solution in [RV03] with query complexity O √ n log(n/m) log m + √ m log 2 m .For readability, these algorithms are postponed to Appendix D.

The Quantum Algorithm for LMSR
Now we are ready to present our quantum algorithm for LMSR and thus prove Theorem 1.1.This algorithm is designed in two steps: 1. Design a quantum algorithm with worst-case query complexity O n 3/4 in Section 5.1; and 2. Improve the algorithm to average-case query complexity O ( √ n log n) in Section 5.2.

The Basic Algorithm
For convenience, we assume that the alphabet Σ = [α] for some α ≥ 2, where [n] = {0, 1, 2, . . ., n−1} and the total order of Σ follows that of natural numbers.Suppose the input string s ∈ Σ n is given by an oracle U in : The overall idea of our algorithm is to split s into blocks of length B, and then in each block find a candidate with the help of the prefix of SCR(s) of length B. These candidates are eliminated between blocks by the exclusion rule for LMSR (see Lemma 5.1).We describe it in detail in the next three subsections.with a constant probability.In the following discussion, we use i * to find possible candidates of LMSR(s) and then find the solution among all candidates.

Candidate in Each Block
Being able to access contents of p by i * , we can obtain a deterministic sample of p by Algorithm 4 in O B log 3 B log log B = Õ( √ B) queries with a constant probability.Suppose a deterministic sample of p is known to be (δ; i 0 , i 1 , . . ., i l−1 ).We split s into blocks of length L = ⌊B/4⌋.In the i-th block (0-indexed, 0 ≤ i < ⌈n/L⌉), with the index ranging from iL to min{(i + 1)L, n} − 1, a candidate h i is computed by where the minimum is taken over all indices j in the i-th block such that s[j . . .j + B − 1] = p, and min ∅ = ∞.Intuitively, for each 0 ≤ i < ⌈n/L⌉, h i defined by Eq. (6) denotes the leftmost possible candidate for LMSR(s) such that s[h i . . .h i + B − 1] = p in the i-th block.On the other hand, h i denotes the first occurrence of p with starting index in the i-th block of s, and thus can be computed by a procedure in quantum pattern matching (see Appendix D for more details), which needs O √ B log B = Õ( √ B) queries to U in with the help of the deterministic sample of p.We write U h for the bounded-error oracle of h i .Note that U h is a 2-level nested quantum oracle.

Candidate Elimination between Blocks
If we know the values of h i for 0 ≤ i < ⌈n/L⌉, with either h i being a candidate or ∞ (indicating non-existence), then we can find LMSR(s) among all h i 's with the comparator where cmp n is defined by Eq. (5), and ∞ can be regarded as n explicitly in the computation.Then we can obtain the bounded-error comparison oracle U cmp corresponding to cmp with constant number of queries to U cmp n and U h , with O √ B log B + √ n queries to U in .Here, U cmp is a 2-level nested quantum oracle.At the end of the algorithm, the value of LMSR(s) is chosen to be the minimal element among h i by comparison oracle U cmp according to comparator cmp.It can be seen that the algorithm is a 3-level nested quantum algorithm.

The Algorithm
We summarize the above design ideas in Algorithm 5.There are four main steps (Line 5, Line 6, Line 7 and Line 8) in the algorithm.Especially, Line 7 of Algorithm 5 involves a 3-level nested quantum algorithm.For convenience, we assume that each of these steps succeeds with a high enough constant probability, say ≥ 0.99.To achieve this, each step just needs a constant number of repetitions to amplify the success probability from 2/3 up to 0.99.
, where cmp is defined by Eq. ( 7).8: return h i , where h i is defined by Eq. ( 6).

Complexity
The query complexity of Algorithm 5 comes from the following four parts: 1 Therefore, the total query complexity is

Correctness
The correctness of Algorithm 5 is not obvious due to the fact that we only deal with one candidate in each block, but there can be several candidates that matches p in a single block.This issue is resolved by the following exclusion rule: • For every two equal substrings s[i . . .i + B − 1] and s[j . . .j + B − 1] of s that overlap each other with 0 ≤ i < j < n and 1 ≤ B ≤ n/2, if both of them are prefixes of SCR(s), then LMSR(s) cannot be the larger index j.
More precisely, this exclusion rule can be stated as the following: Lemma 5.1 (Exclusion Rule for LMSR).Suppose s ∈ Σ n is a string of length n.Let 2 ≤ B ≤ n/2, and two indices i, j Proof.See Appendix E. Indeed, the above exclusion rule can be viewed as the Ricochet Property of LMSR.Here, the Ricochet Property means that if two candidates are in the same block, then at most one of them can survive.This kind of Ricochet property was found to be useful in string matching, e.g., [Vis90].If there are two candidates in the same block, since each block is of length L = ⌊B/4⌋ < B, then the two candidates must overlap each other.By this rule, the smaller candidate remains.Consequently, the correctness of Algorithm 5 is guaranteed because h i defined by Eq. ( 6) always chooses the smallest candidate in each block.
After the above discussions, we obtain: Theorem 5.2.Algorithm 5 is an O n 3/4 bounded-error quantum query algorithm for LMSR.
The quantum algorithm given by Theorem 5.2 uses quantum deterministic sampling (Lemma 4.3) as a subroutine.It can be also made time-efficient in the same way as discussed in Remark 4.2.

An Improvement for Better Average-Case Query Complexity
In the previous subsection, we propose an efficient quantum algorithm for LMSR in terms of its worst-case query complexity.It is easy to see that its average-case query complexity remains the same as its worst-case query complexity.In this subsection, we give an improved algorithm with better average-case query complexity which also retains the worst-case query complexity.
The basic idea is to individually deal with several special cases, which cover almost all of the possibilities on average.Let B = ⌈3 log α n⌉.Our strategy is to just consider substrings of length denote the index of the minimal substring among all substrings of length B, and then let denote the index of the second minimal substring among all substrings of length then it immediately holds that LMSR(s) = k.To find the second minimal substring, the index k of the minimal substring should be excluded.For this, we need comparator cmp B\k : The bounded-error quantum comparison oracle U cmp B\k corresponding to cmp B\k (i, j) can be defined with at most one query to U cmp B .

The Algorithm
Our improved algorithm is presented as Algorithm 6.It has three main steps (Line 5, Line 6 and Line 10).For the same reason as in Algorithm 5, we assume that the third step (Line 10) succeeds with a high enough constant probability, say ≥ 0.99.

Correctness
The correctness of Algorithm 6 is trivial.We only consider the case where n ≥ 4, and all of the three main steps succeed with probability is the minimal substring of length B, and it immediately holds that LMSR(s) = k.Otherwise, the correctness is based on that of BasicLMSR(U in ), which is guaranteed by Theorem 5.2.

Complexity
The worst-case query complexity of Algorithm 6 is O n 3/4 , obtained directly by Theorem 5.2.But settling the average-case query complexity of Algorithm 6 is a bit more subtle, which requires a better understanding of some properties of LMSR.To this end, we first introduce the notion of string sensitivity.
Definition 5.1 (String Sensitivity).Let s ∈ Σ n be a string of length n over a finite alphabet Σ.The string sensitivity of s, denoted C(s), is the smallest positive number l such that s[i . . .i + l − 1] = s[j . . .j + l − 1] for all 0 ≤ i < j < n.In case that no such l exists, define C(s) = ∞.
The string sensitivity of a string is a metric indicating the difficulty to distinguish its rotations by their prefixes.If we know the string sensitivity C(s) of a string s, we can compute LMSR(s) by finding the minimal string among all substrings of s of length The following lemma shows that almost all strings have a low string sensitivity.
It is clear that 0 ≤ d < B. We note that s[i . . .i + B − 1] = s[j . . .j + B − 1] implies the following system of B equations: On the other hand, these B equations involve 2B − d (random) characters.Therefore, there must be (2B − d) − B = B − d independent characters, and the probability that the B equations hold is Consequently, we have: In particular, in the case of B = ⌈3 log α n⌉, it holds that α B ≥ n 3 and we obtain: With the above preparation, we now can analyze the average-case query complexity of Algorithm 6.Let s ∈ Σ n be a uniformly random string over Σ n and B = ⌈3 log α n⌉.Let k and k ′ denote the indices of the minimal and the second minimal substrings of length B of s.To compute k and k ′ , by Lemma 3.5, Algorithm 6 needs to make O √ n log n queries to U cmp B , which is equivalent to queries to U in in order to check whether cmp B (k, k ′ ) = 1, which is ignorable compared to other large complexities.Based on the result of cmp B (k, k ′ ), we only need to further consider the following two cases: Case 1. cmp B (k, k ′ ) = 1.Note that this case happens with probability In this case, Algorithm 6 returns k immediately.Case 2. cmp B (k, k ′ ) = 1.According to Eq. ( 9), this case happens with probability ≤ 1/n.In this case, Algorithm 6 makes one query to BasicLMSR(U in ), which needs O n 3/4 queries to U in (by Theorem 5.2).
Combining the above two cases yields the average-case query complexity of Algorithm 6: After the above discussions, we obtain: Theorem 5.4.Algorithm 6 is an O n 3/4 bounded-error quantum query algorithm for LMSR, whose average-case query complexity is O ( √ n log n).
Algorithm 6 for Theorem 5.4 can be made time-efficient by an argument similar to that given in Section 5.1 for time and space efficiency.

Lower Bounds of LMSR
In this section, we establish average-case and worst-case lower bounds of both classical and quantum algorithms for the LMSR problem and thus prove Theorem 1.2.
The notion of block sensitivity is the key tool we use to obtain lower bounds.Let f : {0, 1} n → {0, 1} be a Boolean function.If x ∈ {0, 1} n is a binary string and S ⊆ [n], we use x S to denote the binary string obtained by flipping the values of x i for i ∈ S, where x i is the i-th character of x: where ū denotes the negation of u, i.e. 0 = 1 and 1 = 0.The block sensitivity of f on input x, denoted bs x (f ), is the maximal number m such that there are m disjoint sets S 1 , S 2 , . . ., S m ⊆ [n] for which f (x) = f (x S i ) for 1 ≤ i ≤ m.

Average-Case Lower Bounds
For settling the average-case lower bound, we need the following useful result about block sensitivities given in [AdW99].
Next, we establish a lower bound for bs x (LMSR 0 ).
where C(x) is the string sensitivity of x.
Proof.We first note that inequality (10) is trivially true when C(x) > n/5 because the right hand side is equal to 0. For the case of C(x) ≤ n/5, our proof is carried out in two steps: Step 1.Let us start from the special case of LMSR(x) = 0. Note that LMSR 0 (x) = 0. Let B = C(x).We split x into (k + 1) substrings x = y 1 y 2 . . .y k y k+1 , where |y i | = B for 1 ≤ i ≤ k, |y k+1 | = n mod B, and k = ⌊n/B⌋.By the assumption that C(x) = B, we have y 1 < min{y 2 , y 3 , . . ., y k }.It holds that y 1 y 2 > 0 2B ; otherwise, y 1 = y 2 = 0 B , and then a contradiction C(x) > B arises.
Let m = ⌊(k − 1)/4⌋.We select some of y i s and divide them into m groups (and the others are ignored).For every 1 ≤ i ≤ m, the i-th group is z i = y 4i−2 y 4i−1 y 4i y 4i+1 .Let L i be the number of characters in front of z i .Then L i = (4i − 3)B.We claim that bs x (LMSR 0 ) ≥ m by explicitly constructing m disjoint sets S 1 , S 2 , . . ., S m ⊆ [n] such that LMSR 0 (x) = LMSR 0 x S i for 1 ≤ i ≤ m: 1.If L i is even, then we define: where δ x,y is the Kronecker delta, that is, δ x,y = 1 if x = y and 0 otherwise.
2. If L i is odd, then we define: Note that S i = ∅, and 0 2B is indeed the substring of x S i that starts at the index Then we conclude that LMSR 0 x S i = 1 for 1 ≤ i ≤ m.Consequently, Step 2. Now we remove the condition that LMSR(x) = 0 in Step 1.Let r = LMSR 0 (x) and we consider the binary string x (r) .Note that LMSR x (r) = 0.By Lemma 6.2, we have: Therefore, inequality (10) holds for all x ∈ {0, 1} n with C(x) ≤ n/5.
We remark that inequality (10) can be slightly improved: , by splitting x more carefully.However, Lemma 6.3 is sufficient for our purpose.With it, we obtain a lower bound of the expected value of bs x (LMSR 0 ) when x is uniformly distributed: Lemma 6.4.Let unif : {0, 1} n → [0, 1] be the uniform distribution that unif (x) = 2 −n for every x ∈ {0, 1} n .Then Combining the above lemma with Theorem 6.5, we conclude that R(LMSR 0 ) = Ω(n) and Q(LMSR 0 ) = Ω ( √ n), which give a lower bound for randomized and one for quantum worst-case bounded-error algorithms for LMSR, respectively.We have another more intuitive proof for the worst-case lower bound for quantum bounded-error algorithms and postpone into Appendix F.

Applications
In this section, we present some practical applications of our quantum algorithm for LMSR.

Benzenoid Identification
The first application of our algorithm is a quantum solution to a problem about chemical graphs.Benzenoid hydrocarbons are a very important class of compounds [Dia87,Dia88] and also popular as mimics of graphene (see [WSS + 08, WMK08, PLB + 16]).Several algorithmic solutions to the identification problem of benzenoids have been proposed in the previous literature; for example, Bašić [Baš16] identifies benzenoids by boundary-edges code [HLZ96] (see also [KPBF14]).Formally, the boundary-edges code (BEC) of a benzenoid is a finite string over a finite alphabet Σ 6 = {1, 2, 3, 4, 5, 6}.The canonical BEC of a benzenoid is essentially the lexicographically maximal string among all rotations of any of its BECs and their reverses.Our quantum algorithm for LMSR can be used to find the canonical BEC of a benzenoid in O n 3/4 queries, where n is the length of its BEC.
More precisely, it is equivalent to find the lexicographically minimal one if we assume that the lexicographical order is 6 < 5 < 4 < 3 < 2 < 1. Suppose a benzenoid has a BEC s.Our quantum algorithm is described as follows: 1 Let i = LMSR(s) and i R = LMSR(s R ), where s R denotes the reverse of s.This is achieved by Algorithm 5 in O(n 3/4 ) query complexity.
2 Return the smaller one between s[i . . .i It is straightforward to see that the overall query complexity is O(n 3/4 ).

Disjoint-Cycle Automata Minimization
Another application of our algorithm is a quantum solution to minimization of a special class of automata.Automata minimization is an important problem in automata theory [HMU00,BBCF10] and has many applications in various areas of computer science.The best known algorithm for minimizing deterministic automata is O(n log n) [Hop71], where n is the number of states.A few linear algorithms for minimizing some special automata are proposed in [Rev92,AZ08], which are important in practice, e.g., dictionaries in natural language processing.We consider the minimization problem of disjoint-cycle automata discussed by Almeida and Zeitoun in [AZ08].The key to this problem is a decision problem that checks whether there are two cycles that are equal to each other under rotations.Formally, suppose there are m cycles, which are described by strings s 1 , s 2 , . . ., s m over a finite alphabet Σ.It is asked whether there are two strings s i and s j (i = j) such that SCR(s i ) = SCR(s j ).For convenience, we assume that all strings are of equal length n, i.e.
A classical algorithm solving the above decision problem was developed in [AZ08] with time complexity O(mn).With the help of our quantum algorithm for LMSR, this problem can be solved more efficiently.We employ a quantum comparison oracle U cmp that compares strings by their canonical representations in the lexicographical order, where the corresponding classical comparator is: cmp(i, j) = 1 SCR(s i ) < SCR(s j ), 0 otherwise, and can be computed by finding r i = LMSR(s i ) and r j = LMSR(s j ).In particular, it can be done by our quantum algorithm for LMSR in O n 3/4 queries.Then the lexicographical comparator in Algorithm 3 can be use to compare s i [r i . . .r i + n − 1] and s j [r j . . .r j + n − 1] in query complexity O n 3/4 .Furthermore, the problem of checking whether there are two strings that are equal to each other under rotations among the m strings may be viewed as the element distinctness problem with quantum comparison oracle U cmp , and thus can be solved by Ambainis's quantum algorithm [Amb07] with Õ m 2/3 queries to U cmp .In conclusion, the decision problem can be solved in quantum time complexity Õ m 2/3 n 3/4 , which is better than the best known classical O(mn) time.

B A Framework of Nested Quantum Algorithms
In this appendix, we provide a general framework to explain how the improvement given in Section 3 can be achieved on nested quantum algorithms composed of quantum search and quantum minimum finding.This framework generalizes multi-level AND-OR trees.In an ordinary AND-OR tree, a Boolean value is given at each of its leaves, and each non-leaf node is associated with an AND or OR operation which alternates in each level.A query-optimal quantum algorithm for evaluation of constantdepth AND-OR trees was proposed in [HMdW03].Our framework can be seen as a generalization of fault tolerant quantum search studied in [HMdW03], which deals with the extended MIN-MAX-AND-OR trees which allow four basic operations and work for non-Boolean cases.Moreover, combining the error reduction idea in [BCdWZ99], we also provide an error reduction for nested quantum algorithms.Our results will be formally stated later in Lemma B.1.
requires the value of f k−1 (θ d−1 , . . ., θ k , i), which in turn requires a constant number of queries to A k−1 with parameters θ d−1 , . . ., θ k , i.The following lemma settles the query complexity of nested quantum algorithms, which shows that nested algorithms can do much better than naively expected.Remark B.2. Lemma B.1 only covers a special case of nested quantum algorithms.A more general form of nested quantum algorithms can be described as a tree rather than a sequence, which allows intermediate quantum algorithms to compute their results by queries to several low-level quantum algorithms.We call them adaptively nested quantum algorithms, and an example of this kind algorithm is presented in Appendix D for pattern matching (see Figure 1).

C Remarks for Quantum Deterministic Sampling
Algorithm 4 uses several nested quantum algorithms as subroutines, but they are not described as nested quantum algorithms explicitly.Here, we provide an explicit description for Line 10 in Algorithm 4 as an example.Let θ 0 ∈ [l] and θ 1 ∈ [n].Then: • The 0-level function is 0 otherwise, which checks whether candidate θ 1 does not match the current deterministic sample at the θ 0 -th checkpoint.
• The 1-level function is which checks candidate θ 1 matches the current deterministic sample at all checkpoints.
• The 2-level function is which finds the first candidate of δ.
By Lemma B.1, f 2 can be computed with error probability

D Quantum Algorithm for Pattern Matching
In this appendix, we give a detailed description of our quantum algorithm for pattern matching.

D.1 Quantum Algorithm for String Periodicity
The algorithm will be presented in the form of a nested quantum algorithm.Suppose a string s ∈ Σ n is given by a quantum oracle U s that U s |i, j = |i, j ⊕ s[i] .We are asked to check whether s is periodic, and if yes, find its period.Let (δ; i 0 , i 1 , . . ., i l−1 ) be a deterministic sample of s.We need a 2-level nested quantum algorithm.Let θ 0 ∈ [l] and θ 1 ∈ [n].Then: • The 0-level function is , which checks whether offset θ 1 matches the deterministic sample at the θ 0 -th checkpoint.
There is obviously an exact quantum oracle that computes f 0 (θ 1 , θ 0 ) with a constant number of queries to U s .
• The 1-level function is where f 1 (θ 1 ) means offset θ 1 matches the deterministic sample of s.The 2-level function is which finds the minimal offset that matches the deterministic sample.
By Lemma B.1, we obtain an O( √ nl) bounded-error quantum algorithm that finds the smallest possible offset δ 1 of the deterministic sample of s.According to δ 1 , we define another 2-level function which finds the second minimal offset that matches the deterministic sample of s, where min ∅ = ∞.Similarly, we can find the second smallest offset δ 2 of the deterministic sample of s in query complexity O √ nl with bounded-error.If δ 2 = ∞, then s is aperiodic; otherwise, s is periodic with period d = δ 2 − δ 1 .Therefore, we obtain an O √ n log n bounded-error quantum algorithm that checks whether a string is periodic and, if yes, finds its period.

D.2 Quantum Algorithm for Pattern Matching
Suppose text t ∈ Σ n and pattern p ∈ Σ m , and a deterministic sample of p is (δ; i 0 , i 1 , . . ., i l−1 ).The idea for pattern matching is to split the text t into blocks of length L = ⌊m/4⌋, the i-th (0-indexed) of which consists of indices ranged from iL to min{(i + 1)L, n} − 1.Our algorithm applies to the case of m ≥ 4, but does not to the case 1 ≤ m ≤ 3, where a straightforward quantum search is required (we omit it here).
The key step for pattern matching is to find a candidate h i for 0 ≤ i < ⌈n/L⌉, indicating the first occurrence in the i-th block with starting index iL ≤ j < min{(i + 1)L, n}, where j + m ≤ n and t[j . . .j + m − 1] = p.Formally, where min ∅ = ∞.Note that Eq. ( 6) is similar to Eq. ( 11) but without the condition of j + m ≤ n, which can easily removed from our algorithm given in the following discussion.In the previous subsection, we presented an efficient quantum algorithm that checks whether the string is periodic or not.Then we are able to design an quantum algorithm for pattern matching.Let us consider the cases of aperiodic patterns and periodic patterns, separately:

D.2.1 Aperiodic Patterns
The Algorithm.For an aperiodic pattern p, h i can be computed in the following two steps: 1. Search j from iL ≤ j < min{(i + 1)L, n} such that t[i k − δ + j] = p[i k − δ] for every k ∈ [l] (we call such j a candidate of matching).For every j, there is an O( √ l) bounded-error quantum algorithm to check whether t Correctness.Note that in the i-th block, if there is no such j or there are more than two values of j such that t[i k − δ + j] = p[i k − δ] for every k ∈ [l], then there is no matching in the i-th block.More precisely, we have: Lemma D.1 (The Ricochet Property [Vis90]).Let p ∈ Σ m be aperiodic, (δ; i 0 , i 1 , . . ., i l−1 ) be a deterministic sample, and t ∈ Σ n be a string of length n ≥ m, and let j ∈ Proof.Assume that t[j ′ . . .j ′ + m − 1] = p for some j − δ ≤ j ′ < j − δ + ⌊m/2⌋.Let x = δ − j + j ′ .Note that 0 ≤ x < ⌊m/2⌋.We further assume that x = δ.Then by the definition of a deterministic sample, there exists k ∈ A contradiction arises, which implies x = δ and therefore j = j ′ .We can see that if there are two different indices j 1 , j 2 in the i-th block such that t[i k − δ + j r ] = p[i k − δ] for every k ∈ [l] and r ∈ {1, 2}, it must hold that |j 1 − j 2 | ≤ m/4, since each block has length L = ⌊m/4⌋.If we apply Lemma D.1 on j 1 , then t[j 2 . . .j 2 + m − 1] = p; and if we apply it on j 2 , then t[j 1 . . .j 1 + m − 1] = p.Thus, we conclude that neither j 1 nor j 2 can be a starting index of occurrence p in t.As a result, there is at most one candidate of matching in each block.
A Description in the Form of a Nested Quantum Algorithm.The above algorithm can be more clearly described as a 3-level nested quantum algorithm.
• The level-0 function is defined by which checks whether t matches p at the θ 0 -th checkpoint at the θ 1 -th index in the θ 2 -th block, where θ • The level-1 function is defined by which checks whether t matches the deterministic sample at the θ 1 -th index in the θ 2 -th block.
• The level-3 function f 3 finds a matching among f 2 (i) over all i ∈ [⌈n/L⌉] by checking whether iL + f 2 (i) + m ≤ n and t[iL + f 2 (i) . . .iL + f 2 (i) + m − 1] = p, where the latter condition can be checked by a quantum searching algorithm, which can be formulated as a 1-level nested quantum algorithm: -The level-0 function -The 1-level function which checks whether the substring of t starting at offset ξ 1 in the ξ 2 -th block matches p. Finally, we have that f 3 finds a solution i ∈ [⌈n/L⌉] such that iL + f 2 (i) + m ≤ n and g 1 (i, f 2 (i)) = 1.
The structure of our algorithm can be visualized as the tree in Figure 1.It is worth noting that f 3 calls both f 2 and g 1 .
By a careful analysis, we see that the query complexity of the above algorithm is O √ n log m .

D.2.2 Periodic Patterns
For a periodic pattern p, a similar result can be achieved with some minor modifications to the algorithm for an aperiodic pattern.First, we have: Proof.Similar to proof of Lemma D.1.Now in order deal with periodic pattern p, the algorithm for an aperiodic pattern can be modified as follows.For the i-th block, in order to compute h i , we need to find (by minimum finding) the leftmost and the rightmost candidates j l and j r , which requires O √ Ll = O √ m log m queries (by Algorithm 1).Let us consider two possible cases: 1.If j l ≡ j r (mod d), then by Lemma D.2, there is no matching in the i-th block and thus h i = ∞; 2. If j l ≡ j r (mod d), find the smallest j l ≤ q ≤ R i such that t[q . . .R i ] = p[q−j l . . .q−j l +R i −q], where R i = min{(i + 1)L, n} − 1 denotes the right endpoints of the i-th block, by minimum finding in O √ L = O ( √ m) queries (by Algorithm 1).Then the leftmost candidate will be j = j l + q − j l d d.
If j ≤ min {n − m, j r } and t[j . . .j + m − 1] = p (which can be checked by quantum search in O( √ m) queries), then h i = j; otherwise, h i = ∞.
Correctness.It is not straightforward to see that the leftmost occurrence in the i-th block is found in the case j l ≡ j r (mod d) if there does exist an occurrence in that block.By Lemma D.2, if there exists an occurrence starting at index j l ≤ j ≤ j r in the i-th block, then j l ≡ j ≡ j r (mod d).
Let the leftmost and the rightmost occurrences of p in the i-th block be j ′ l and j ′ r , respectively.Then j l ≤ j ′ l ≤ j ′ r ≤ j r and j l ≡ j ′ l ≡ j ′ r ≡ j r (mod d).By the minimality of q with j l ≤ q ≤ R i and Figure 1: Quantum pattern matching algorithm for aperiodic strings.
t[q . . .R i ] = p[q − j l . . .q − j l + R i − q], we have q ≤ j ′ l , and therefore the candidate determined by q is j q = j l + q − j l d d ≤ j ′ l .
On the other hand, if j q = j ′ l , the existence of j ′ l leads immediately to that t[j q . . .j q + m − 1] matches p, i.e. j q < j ′ l is also an occurrence, which contradicts with the minimality of j ′ l .As a result, we have j q = j ′ l .That is, our algorithm finds the leftmost occurrence in the block, if exists.Complexity.According to the above discussion, it is clear that h i can be computed with bounded-error in O √ m log m queries.Thus, the entire problem can be solved by searching on bounded-error oracles (by Theorem 3.1) and the query complexity is Combining the above two cases, we conclude that there is a bounded-error quantum algorithm for pattern matching in O √ n log m + m log 3 m log log m queries.

E Proof of Exclusion Rule for LMSR
In this appendix, we present a proof of Lemma 5.1.To this end, we first observe:

F Worst-case Quantum Lower Bound
The worst-case quantum lower bound can be examined in a way different from that in Section 6.2.Let us consider a special case where all strings are binary, that is, the alphabet is Σ = {0, 1}.A solution to the LMSR problem implies the existence of a 0 character.That is, s[i] = 0 for some i ∈ [n] if and only if s[LMSR(s)] = 0. Therefore, the search problem can be reduced to LMSR.It is known that the search problem has a worst-case query complexity lower bound Ω ( √ n) for bounded-error quantum algorithms [BBBV97, BBHT98, Zal99], and Ω(n) for exact and zero-error quantum algorithms [BBC + 01].Consequently, we assert that the LMSR problem also has a worstcase quantum query complexity lower bound Ω ( √ n) for bounded-error quantum algorithms, and Ω(n) for exact and zero-error quantum algorithms.

For
any positive number n, let [n] = {0, 1, 2, . . ., n − 1}.Let Σ be a finite alphabet with a total order <.A string s ∈ Σ n of length n is a function s : [n] → Σ.The empty string is denoted ǫ.We use s[i] to denote the i-th character of s.In case of i / ∈ Z \ [n], we define s[i] ≡ s[i mod n].If l ≤ r, s[l . . .r] = s[l]s[l + 1] . . .s[r] stands for the substring consisting of the l-th to the r-th character of s, and if l > r, we define s[l . . .r] = ǫ.A prefix of s is a string of the form s[0 . . .i] for i ∈ [n] ∪ {−1}.

2.
At step k ≥ 0, let δ min k = min A k and δ max k = max A k .2.1.If δ min k = δ max k , then set δ = δ min k and return the current set S k of checkpoints.
4 has O n log(1/ε) = O √ n log log n queries to U x (by Lemma 3.5), and Seach has query complexity O n log(1/ε) = O √ n log log n (by Theorem 3.2).Hence, a single iteration has query complexity O √ nl log log n = O √ n log n log log n , and the total query complexity (m iterations) is O m √ n log n log log n = O n log 3 n log log n .Algorithm 4 is a 2-level nested quantum algorithm (see Appendix C for a more detailed discussion), and is a better solution for deterministic sampling in O n log 3 n log log n queries than the known O √ n log 2 n solution in [RV03].

Lemma B. 1 (
Nested quantum algorithms).Given a d-level nested quantum algorithm A 1 , A 2 , . . ., A d , where d ≥ 2, and n 0 , n 1 , . . ., n d−1 , S m , f d are defined as above.Then: 1.There is a bounded-error quantum algorithm that computes f d with query complexity O is a quantum algorithm that computes f d with error probability ≤ ε with query complexity Immediately yields by Theorem 3.1, Theorem 3.2, Lemma 3.4 and Lemma 3.5.Remark B.1.Lemma B.1 can be seen as a combination of Theorem 3.1, Theorem 3.2, Lemma 3.4 and Lemma 3.5.For convenience, we assume n 0 = n 1 = • • • = n d−1 = n in the following discussions.Note that traditional probability amplification methods for randomized algorithms usually introduce an O log d−1 n slowdown for d-level nested quantum algorithms by repeating the algorithm O(log n) times in each level.However, our method obtains an extremely better O(1) factor as if there were no errors in oracles at all.

Table 2 :
Classical and quantum query complexities of LMSR, canonical boundary-edges code and disjoint-cycle automata minimization.For disjoint-cycle automata minimization, m indicates the number of disjoint cycles and n indicates the length of each cycle.Here, Õ(•) suppresses logarithmic factors.

Table 3 :
[BCW98,HMdW03]complexities of bounded-error quantum algorithms and their error reductions for search and minimum finding.AND-OR trees and optimally O√ n d as known from[BCW98,HMdW03].Our improvements on these problems are summarized in Table4.
√ n log(n/m) log m + √ m log 2 m).We also develop an optimal O √ n d quantum algorithm for evaluating d-level shallow MIN-MAX trees that matches the lower bound Ω √ n d [Amb00, BS04] for AND-OR trees, and therefore it is optimal.The best known previous quantum query complexity of MIN-MAX trees is O (W d (n) log n) [CGYM08], where W d (n) is the query complexity of d-level According to Algorithm 3, we can obtain a bounded-error comparison oracle U cmp B corresponding to cmp B with O √ B queries to U in .After that, let i * ∈ [n] be any index such that s[i * . . .i * +B−1] = p by calling Minimum(U cmp B ), which needs O ( √ n) queries to U cmp B (by Lemma 3.4) and succeeds * ∈ [n] such that s[i * . . .i * + B − 1] matches p, where B = ⌊ √ n⌋ is chosen optimally (see later discussions).To achieve this, we need to compare two substrings of s of length B with the comparator cmp B : cmp B (i, j) = 1 s[i . . .i + B − 1] < s[j . . .j + B − 1 Algorithm 5 BasicLMSR(U in ): Quantum algorithm for LMSR.Input: The query oracle U in for string s.Output: LMSR(s) with probability ≥ 2/3.
Algorithm 6 ImprovedLMSR(U in ): Improved quantum algorithm for LMSR.Input: The query oracle U in for string s.Output: LMSR(s) with probability ≥ 2/3.Minimum(U cmp B , 1/2n), where cmp B is defined by Eq. (5).6: k ′ ← Minimum(U cmp B\k , 1/2n), where cmp B\k is defined by Eq. (8).7: if cmp B (k, k ′ ) = 1 then 1: if n ≤ 3 then 5: k ← If the found index j does not satisfy this condition, then h i = ∞; otherwise, h i = j.It is clear that h i can be computed with bounded-error in O√ m log m queries according to the above discussion.Recall that p appears in t at least once, if and only if there is at least a 0 ≤ i < ⌈n/L⌉ such that h i = 1.By Theorem 3.1, this can be checked in O 2. Check whether the index j found in the previous step satisfies j +m ≤ n and t[j . . .j +m−1] = p.This can be computed by quantum search in O ( √ m) queries.