Tight Tradeoffs for Real-Time Approximation of Longest Palindromes in Streams

We consider computing a longest palindrome in the streaming model, where the symbols arrive one-by-one and we do not have random access to the input. While computing the answer exactly using sublinear space is not possible in such a setting, one can still hope for a good approximation guarantee. Our contribution is twofold. First, we provide lower bounds on the space requirements for randomized approximation algorithms processing inputs of length $n$. We rule out Las Vegas algorithms, as they cannot achieve sublinear space complexity. For Monte Carlo algorithms, we prove a lower bounds of $\Omega( M \log\min\{|\Sigma|,M\})$ bits of memory; here $M=n/E$ for approximating the answer with additive error $E$, and $M= \frac{\log n}{\log (1+\varepsilon)}$ for approximating the answer with multiplicative error $(1 + \varepsilon)$. Second, we design three real-time algorithms for this problem. Our Monte Carlo approximation algorithms for both additive and multiplicative versions of the problem use $O(M)$ words of memory. Thus the obtained lower bounds are asymptotically tight up to a logarithmic factor. The third algorithm is deterministic and finds a longest palindrome exactly if it is short. This algorithm can be run in parallel with a Monte Carlo algorithm to obtain better results in practice. Overall, both the time and space complexity of finding a longest palindrome in a stream are essentially settled.


Introduction
In the streaming model of computation, a very long input arrives sequentially in small portions and cannot be stored in full due to space limitation. While well-studied in general, this is a rather recent trend in algorithms on strings. The main goals are minimizing the space complexity, i.e., avoiding storing the already seen prefix of the string explicitly, and designing real-time algorithm, i.e., processing each symbol in worstcase constant time. However, the algorithms are usually randomized and return the correct answer with high probability. The prime example of a problem on string considered in the streaming model is pattern matching, where we want to detect an occurrence of a pattern in a given text. It is somewhat surprising that one can actually solve it using polylogarithmic space in the streaming model, as proved by Porat and Porat [15]. A simpler solution was later given by Ergün et al. [6], while Breslauer and Galil designed a real-time algorithm [3]. Similar questions studied in such setting include multiple-pattern matching [4], approximate pattern matching [5], and parametrized pattern matching [10].
We consider computing a longest palindrome in the streaming model, where a palindrome is a fragment which reads the same in both directions. This is one of the basic questions concerning regularities in texts and it has been extensively studied in the classical non-streaming setting, see [1,8,12,14] and the references therein. The notion of palindromes, but with a slightly different meaning, is very important in computational biology, where one considers strings over {A, T, C, G} and a palindrome is a sequence equal to its reverse complement (a reverse complement reverses the sequences and interchanges A with T and C with G); see [9] and the references therein for a discussion of their algorithmic aspects. Our results generalize to biological palindromes in a straightforward manner.
We denote by LPS(S) the problem of finding the maximum length of a palindrome in a string S (and a starting position of a palindrome of such length in S). Solving LPS(S) in the streaming model was recently considered by Berenbrink et al. [2], who developed tradeoffs between the bound on the error and the space complexity for additive and multiplicative variants of the problem, that is, for approximating the length of the longest palindrome with either additive or multiplicative error. Their algorithms were Monte Carlo, i.e., returned the correct answer with high probability. They also proved that any Las Vegas algorithm achieving additive error E must necessarily use Ω( n E log |Σ|) bits of memory, which matches the space complexity of their solution up to a logarithmic factor in the E ∈ [1, √ n] range, but leaves a few questions. Firstly, does the lower bound still hold for Monte Carlo algorithms? Secondly, what is the best possible space complexity when E ∈ ( √ n, n] in the additive variant, and what about the multiplicative version? Finally, are there real-time algorithms achieving these optimal space bounds? We answer all these questions. Our main goal is to settle the space complexity of LPS. We start with the lower bounds in Sect. 2. First, we show that Las Vegas algorithms cannot achieve sublinear space complexity at all. Second, we prove a lower bound of Ω(M log min{|Σ|, M }) bits of memory for Monte Carlo algorithms; here M = n/E for approximating the answer with additive error E, and M = log n log(1+ε) for approximating the answer with multiplicative error (1+ε). Then, in Sect. 3 we design real-time Monte Carlo algorithms matching these lower bounds up to a logarithmic factor. More precisely, our algorithm for LPS with additive error E ∈ [1, n] uses O(n/E) words of space, while our algorithms for LPS with multiplicative error ε ∈ (0, 1] (resp., ε ∈ (1, n]) uses O log(nε) ε (resp., O( log n log(1+ε) )) words of space 1 . Finally we present, for any m, a deterministic O(m)space real-time algorithm solving LPS exactly if the answer is less than m and detecting a palindrome of length ≥ m otherwise. The last result implies that if the input stream is fully random, then with high probability its longest palindrome can be found exactly by a real-time algorithm within logarithmic space. .j] (resp., S[j..n]). A string S is a palindrome if it equals its reversal S[n]S[n−1] · · · S [1]. By L(S) we denote the length of a longest palindrome which is a factor of S. The symbol log stands for the binary logarithm.
We consider the streaming model of computation: the input string S[1.
.n] (called the stream) is read left to right, one symbol at a time, and cannot be stored, because the available space is sublinear in n. The space is counted as the number of O(log n)-bit machine words. An algorithm is real-time if the number of operations between two reads is bounded by a constant. An approximation algorithm for a maximization problem has additive error E (resp., multiplicative error ε) if it finds a solution with the cost at least OP T −E (resp., OP T 1+ε ), where OP T is the cost of optimal solution; here both E and ε can be functions of the size of the input. In the LPS(S) problem, OP T = L(S).
A Las Vegas algorithm always returns a correct answer, but its working time and memory usage on the inputs of length n are random variables. A Monte Carlo algorithm gives a correct answer with high probability (greater than 1 − 1/n) and has deterministic working time and space.

Lower Bounds
In this section we use Yao's minimax principle [17] to prove lower bounds on the space complexity of the LPS problem in the streaming model, where the length n and the alphabet Σ of the input stream are specified. We denote this problem by LPS Σ [n].
Theorem 2.1 (Yao's minimax principle for randomized algorithms). Let X be the set of inputs for a problem and A be the set of all deterministic algorithms solving it. Then, for any x ∈ X and A ∈ A, the cost of running A on x is denoted by c(a, x) ≥ 0.
Let p be the probability distribution over A, and let A be an algorithm chosen at random according to p. Let q be the probability distribution over X , and let X be an input chosen at random according to q. Then We use the above theorem for both Las Vegas and Monte Carlo algorithms. For Las Vegas algorithms, we consider only correct algorithms, and c(x, a) is the memory usage. For Monte Carlo algorithms, we consider all algorithms (not necessarily correct) with memory usage not exceeding a certain threshold, and c(x, a) is the correctness indicator function, i.e., c(x, a) = 0 if the algorithm is correct and c(x, a) = 1 otherwise.
Our proofs will be based on appropriately chosen padding. The padding requires a constant number of fresh characters. If Σ is twice as large as the number of required fresh characters, we can still use half of it to construct a difficult input instance, which does not affect the asymptotics. Otherwise, we construct a difficult input instance over Σ, then add enough new fresh characters to facilitate the padding, and finally reduce the resulting larger alphabet to binary at the expense of increasing the size of the input by a constant factor. Clearly |h(c)| = 2σ + 6 and, because every h(c) is a palindrome, if w contains a palindrome of length then h(w) contains a palindrome of length (2σ + 6) · . Now assume that h(w) contains a palindrome of length (2σ + 6) · , where ≥ 1. If = 1 then we obtain that w should contain a palindrome of length 1, which always holds. Otherwise, the palindrome contains 00 inside and we consider two cases.
1. The palindrome is centered inside 00. Then it corresponds to an odd palindrome of length in w.
2. The palindrome maps some 00 to another 00. Then it corresponds to an even palindrome of length in w.
In either case, the claim holds.
For the padding we will often use an infinite string ν = 0 1 1 1 0 2 1 2 0 3 1 3 . . ., or more precisely its prefixes of length d, denoted ν(d). Here 0 and 1 should be understood as two characters not belonging to the original alphabet. The longest palindrome in ν(d) has length O( √ d).
Proof. By Theorem 2.1, it is enough to construct a probability distribution P over Σ n such that for any deterministic algorithm D, its expected memory usage on a string chosen according to P is Ω(n log |Σ|) in bits.
Consider solving LPS Σ [n] with additive error E. We define P as the uniform distribution over ν( E 2 )x$$yν( E 2 ) R , where x, y ∈ Σ n , n = n 2 − E 2 − 1, and $ is a special character not in Σ. Let us look at the memory usage of D after having read ν( E 2 )x. We say that x is "good" when the memory usage is at most n 2 log |Σ| and "bad" otherwise. Assume that 1 2 |Σ| n of all x's are good, then there are two strings x = x such that the state of D after having read both ν( E 2 )x and ν( E 2 )x is exactly the same. Hence the behavior of D on ν( The former is a palindrome of length n = 2n + E + 2, so D must answer at least 2n + 2, and consequently the latter also must contain a palindrome of length at least x , x R or it is a middle palindrome. But the longest palindrome inside ν( E 2 ) is of length O( √ E) < 2n + 2 (for n large enough) and the longest palindrome inside x or x R is of length n < 2n + 2, so since we have exluced other possibilities, ν( E 2 )x $$x R ν( E 2 ) R contains a middle palindrome of length 2n + 2. This implies that x = x , which is a contradiction. Therefore, at least 1 2 |Σ| n of all x's are bad. But then the expected memory usage of D is at least n 4 log |Σ|, which for E ≤ 0.99n is Ω(n log |Σ|) as claimed. Now consider solving LPS Σ [n] with multiplicative error (1 + ε). An algorithm with multiplicative error (1 + ε) can also be considered as having additive error E = n · ε 1+ε , so if the expected memory usage of such an algorithm is o(n log |Σ|) and (1 + ε) ≤ 100 then we obtain an algorithm with additive error E ≤ 0.99n and expected memory usage o(n log |Σ|), which we already know to be impossible. Now we move to Monte Carlo algorithms. We first consider exact algorithms solving LPS Σ [n]; lower bounds on approximation algorithms will be then obtained by padding the input appropriately. We introduce an auxiliary problem midLPS Σ [n], which is to compute the length of the middle palindrome in a string of even length n over an alphabet Σ.
Lemma 2.4. There exists a constant γ such that any randomized Monte Carlo streaming algorithm A solving midLPS Σ [n] or LPS Σ [n] exactly with probability 1 − 1 n uses at least γ · n log min{|Σ|, n} bits of memory. Proof. First we prove that if A is a Monte Carlo streaming algorithm solving midLPS Σ [n] exactly using less than n 2 log |Σ| bits of memory, then its error probability is at least 1 n|Σ| . By Theorem 2.1, it is enough to construct probability distribution P over Σ n such that for any deterministic algorithm D using less than n 2 log |Σ| bits of memory, the expected probability of error on a string chosen according to P is at least 1 n|Σ| . Let n = n 2 . For any x ∈ Σ n , k ∈ {1, 2, . . . , n } and c ∈ Σ we define Now P is the uniform distribution over all such w(x, k, c).
Choose an arbitrary maximal matching of strings from Σ n into pairs (x, x ) such that D is in the same state after reading either x or x . At most one string per state of D is left unpaired, that is at most 2 n 2 log |Σ| −1 strings in total. Since there are |Σ| n = 2 n log |Σ| ≥ 2 · 2 n 2 log |Σ| −1 possible strings of length n , at least half of the strings are paired. Let s be longest common suffix of x and x , so x = vcs and x = v c s, where c = c are single characters. Then D returns the same answer on w(x, n − |s|, c) and w(x , n − |s|, c), even though the length of the middle palindrome is exactly 2|s| in one of them, and at least 2|s| + 2 in the other one. Therefore, D errs on at least one of these two inputs. Similarly, it errs on either w(x, n − |s|, c ) or w(x, n − |s|, c ). Thus the error probability is at least 1 2n |Σ| = 1 n|Σ| . Now we can prove the lemma for midLPS Σ [n] with a standard amplification trick. Say that we have a Monte Carlo streaming algorithm, which solves midLPS Σ [n] exactly with error probability ε using s(n) bits of memory. Then we can run its k instances simultaneously and return the most frequently reported answer. The new algorithm needs O(k · s(n)) bits of memory and its error probability ε k satisfies: 1+log |Σ|/ log n = Θ( log n log n+log |Σ| ) = γ · 1 log |Σ| log min{|Σ|, n}, for some constant γ. Now we can prove the theorem. Assume that A uses less than κ · n log |Σ| = γ · n log min{|Σ|, n} bits of memory. Then running 1 2κ ≥ 3 4 1 2κ (which holds since κ < 1 6 ) instances of A in parallel requires less than n 2 log |Σ| bits of memory. But then the error probability of the new algorithm is bounded from above by 4 n Now if the length of the middle palindrome in x is k, then w(x) contains a palindrome of length at least n + k + 2. In the other direction, any palindrome inside w(x) of length ≥ n must be centered somewhere in the middle block consisting of only zeroes and both ones are mapped to each other, so it must be the middle palindrome. Thus, the length of the longest palindrome inside w(x) is exactly n + k + 2, so we have reduced solving midLPS Σ [n] to solving LPS Σ [2n + 2]. We already know that solving midLPS Σ [n] with probability 1 − 1 n requires γ · n log min{|Σ|, n} bits of memory, so solving LPS Σ [2n + 2] with probability 1 − 1 2n+2 ≥ 1 − 1 n requires γ · n log{|Σ|, n} ≥ γ · (2n + 2) log min{|Σ|, 2n + 2} bits of memory. Notice that the reduction needs O(log n) additional bits of memory to count up to n, but for large n this is much smaller than the lower bound if we choose γ < γ 4 . To obtain a lower bound for Monte Carlo additive approximation, we observe that any algorithm solving LPS Σ [n] with additive error E can be used to solve LPS Σ [ n−E E+1 ] exactly by inserting E 2 zeroes between every two characters, in the very beginning, and in the very end. However, this reduction requires log( E 2 ) ≤ log n additional bits of memory for counting up to E 2 and cannot be used when the desired lower bound on the required number of bits Ω( n E log min(|Σ|, n E ) is significantly smaller than log n. Therefore, we need a separate technical lemma which implies that both additive and multiplicative approximation with error probability 1 n require Ω(log n) bits of space. Lemma 2.5. Let A be any randomized Monte Carlo streaming algorithm solving LPS Σ [n] with additive error at most 0.99n or multiplicative error at most n 0.49 and error probability 1 n . Then A uses Ω(log n) bits of memory.
Proof. By Theorem 2.1, it is enough to construct a probability distribution P over Σ n , such that for any deterministic algorithm D using at most s(n) = o(log n) bits of memory, the expected probability of error on a string chosen according to P is Observe that if x = y then w(x, y) contains a palindrome of length n, and otherwise the longest palindrome there has length at most , thus any algorithm with additive error of at most 0.99n or with a multiplicative error at most n 0.49 must be able to distinguish between these two cases (for n large enough).
Let S ⊆ Σ n be an arbitrary family of strings of length n such that |S| = 2 · 2 s(n) , and let P be the uniform distribution on all strings of the form w(x, y), where x and y are chosen uniformly and independently from S. By a counting argument, we can create at least |S| 4 pairs (x, x ) of elements from S such that the state of D is the same after having read ν( n 2 − n ) R x and ν( n 2 − n ) R x . (If we create the pairs greedily, at most one such x per state of memory can be left unpaired, so at least |S| − 2 s(n) = |S| 2 elements are paired.) Thus, D cannot distinguish between w(x, x ) and w(x, x), and between w(x , x ) and w(x , x), so its error probability must be at least |S|/2 , the error rate is at least 1 n for n large enough, a contradiction.
Combining the reduction with the technical lemma and taking into account that we are reducing to a problem with string length of Θ( n E ), we obtain the following. Theorem 2.6 (Monte Carlo additive approximation). Let A be any randomized Monte Carlo streaming algorithm solving LPS Σ [n] with additive error E with probability 1 − 1 n . If E ≤ 0.99n then A uses Ω( n E log min{|Σ|, n E }) bits of memory.
Proof. Define σ = min{|Σ|, n E }. Because of Lemma 2.5 it is enough to prove that Ω( n E log σ) is a lower bound when Assume that there is a Monte Carlo streaming algorithm A solving LPS Σ [n] with additive error E using o( n E log σ) bits of memory and probability 1 − 1 n . Let n = n−E/2 E/2+1 ≥ n E (the last inequality, equivalent to n ≥ E · E E−2 holds because E ≤ 0.99n and because we can assume that E ≥ 200). Given a string log(E/2) ≤ log n additional bits of memory), and then return R E/2+1 . We call this new Monte Carlo streaming algorithm A . Recall that A reports the length of the longest palindrome with additive error E. Therefore, if the original string contains a palindrome of length r, the new string contains a palindrome of length E 2 · (r + 1) + r, so R ≥ r(E/2 + 1) and A will return at least r. In the other direction, if A returns r, then the new string contains a palindrome of length r(E/2 + 1). If such palindrome is centered so that x[i] is matched with x[i + 1] for some i, then it clearly corresponds to a palindrome of length r in the original string. But otherwise every x[i] within the palindrome is matched with 0, so in fact the whole palindrome corresponds to a streak of consecutive zeroes in the new string and can be extended to the left and to the right to start and end with 0 E , so again it corresponds to a palindrome of length r in the original string. Therefore, A solves LPS Σ [n ] exactly with probability 1 − (where the last inequality holds because of Eq. (1)). Then, for large n we obtain contradiction as follows o(n log σ) + log n < γ 2 · n log σ + log n.
Finally, we consider multiplicative approximation. The proof follows the same basic idea as of Theorem 2.6, however is more technically involved. The main difference is that due to uneven padding, we are reducing to midLPS Σ [n ] instead of LPS Σ [n ].

Real-Time Algorithms
In this section we design real-time Monte Carlo algorithms within the space bounds matching the lower bounds from Sect. 2 up to a factor bounded by log n. The algorithms make use of the hash function known as the Karp-Rabin fingerprint [11]. Let p be a fixed prime from the range [n 3+α , n 4+α ] for some α > 0, and r be a fixed integer randomly chosen from {1, . . . , p−1}. For a string S, its forward hash and reversed hash are defined, respectively, as Clearly, the forward hash of a string coincides with the reversed hash of its reversal. Thus, if u is a palindrome, then φ F (u) = φ R (u). The converse is also true modulo the (improbable) collisions of hashes, because for two strings u = v of length m, the probability that φ F (u) = φ F (v) is at most m/p. This property allows one to detect palindromes with high probability by comparing hashes. (This approach is somewhat simpler than the one of [2]; in particular, we do not need "fingerprint pairs" used there.) In particular, a real-time algorithm makes O(n) comparisons and thus faces a collision with probability O(n −1−α ) by the choice of p. All further considerations assume that no collisions happen. For an input stream S, we denote . The next observation is quite important.
). The following equalities hold: The proposition below is immediate from definitions and Proposition 3.1.  First we present a simple (and slow) algorithm which solves the posed problem, i.e., finds in S a palindrome of length (S) ≥ L(S) − E, where L(S) is the length of the longest palindrome in S. Later this algorithm will be converted into a real-time one. We store the sets I(j) for some values of j in a doubly-linked list SP in the decreasing order of j's. The longest palindrome currently found is stored as a pair answer = (pos, len), where pos is its initial position and len is its length. Let t E = E 2 . In Algorithm ABasic we add I(j) to the list SP for each j divisible by t E . This allows us to check for palindromicity, at ith iteration, all factors of the form S[kt E ..i]. We assume throughout the section that at the beginning of ith iteration the value I(i) is stored in a variable I.

Additive Error
At the kth iteration, I(k) was added to SP ; then the palindrome S[k..j−(k−i)] was found at the iteration j − (k − i). Its length is as required.
The resource to speed up Algorithm ABasic stems from the following Lemma 3.5. During one iteration, the length answer.len increases by at most 2 · t E .
Proof. Let S[j..i] be the longest palindrome found at the ith iteration. If i − j + 1 ≤ 2t E then the statement is obviously true. Otherwise the palindrome S[j+t E ..i−t E ] of length i − j + 1 − 2t E was found before (at the (i−t E )th iteration), and the statement holds again.
Lemma 3.5 implies that at each iteration SP contains only two elements that can increase answer.len. Hence we get the following Algorithm A.
Due to Lemma 3.5, the cycle at lines 9-11 of Algorithm A computes the same sequence of values of answer as the cycle at lines 4-6 of Algorithm ABasic. Hence it finds a palindrome of required length by Proposition 3.4. Clearly, the space used by the two algorithms differs by a constant. To prove that an iteration of Algorithm A takes O(1) time, it suffices to note that the cycle in lines 7-8 performs at most two iterations. Theorem 3.3 is proved.
As in the previous section, we first present a simpler algorithm MBasic with non-linear working time and then upgrade it to a real-time algorithm. The algorithm must find a palindrome of length (S) ≥ L(S) 1+ε . The next lemma is straightforward.
We set q ε = log 2 ε . The main difference in the construction of algorithms with the multiplicative and additive error is that here all sets I(i) are added to the list SP , but then, after a certain number of steps, are deleted from it. The number of iterations the set I(i) is stored in SP is determined by the time-to-live function ttl (i) defined below. This function is responsible for both the correctness of the algorithm and the space bound.
Let β(i) be the position of the rightmost 1 in the binary representation of i (the position 0 corresponds to the least significant bit). We define ttl (i) = 2 qε+2+β(i) .
The definition is illustrated by Fig. 1. Next we state a few properties of the list SP .   Figure 1: The state of the list SP after the iteration i = 53 (q ε = 1 is assumed). Black squares indicate the numbers j for which I(j) is currently stored. For example, (9) implies ttl (28) = 2 1+2+2 = 32, so I(28) will stay in SP until the iteration 28 + 32 = 60.
Proof. By (9), ttl (j) ≥ 2 qε+2+b if and only if β(j) ≥ b, i.e., j is divisible by 2 b by the definition of β. Among any 2 b consecutive integers, exactly one has this property. Figure 1 shows the partition of the range (0, i] into intervals having lengths that are powers of 2 (except for the leftmost interval). In general, this partition consists of the following intervals, right to left: Lemma 3.8 and (9) imply the following lemma on the distribution of the elements of SP . Lemma 3.9. After each iteration, the first interval (resp., the last interval; each of the remaining intervals) in (10) contains 2 qε+2 (resp., at most 2 qε+1 ; exactly 2 qε+1 ) elements of the list SP . (10) is O(log(nε)), so from Lemma 3.9 and the definition of q ε we have the following. .j] will be found exactly, because I(i) is in SP at the jth iteration:

The number of the intervals in
Otherwise, by Lemma 3.8 there exists a unique k ∈ [i, i + 2 d−qε−1 ) such that ttl (k) ≥ 2 d+1 . Hence at the iteration j −(k −i) the palindrome S[i+(k−i)..j−(k−i)] will be found, because I(k) is in SP at this iteration: The length of this palindrome satisfies the requirement of the proposition: The reference to Lemma 3.7 finishes the proof.  Proof. Let j be the number of the considered iteration. Note that a < b < c < d. Consider the interval in (10) containing a. If a ∈ (j − 2 qε+2 , j], then b − a = 1 and d − b = 2, so the required inequality holds. Otherwise, let a ∈ (j −2 qε+2+x , j −2 qε+2+x−1 ]. Then by (9) β(a) ≥ x; moreover, any I(k) such that a < k ≤ j and β(k) ≥ x is in SP . Hence, b − a ≤ 2 x . By Lemma 3.9 each interval, except for the leftmost one, contains at least 2 qε+1 ≥ 4 elements. Thus each of the numbers b, c, d belongs either to the same interval as a or to the previous interval (j − 2 qε+2+x−1 , j − 2 qε+2+x−2 ]. Again by (9)    Proof. Note that β(x + ttl (x)) = β(x) from the definition of ttl . Hence the equality x + ttl (x) = y + ttl (y) implies β(x) = β(y), then ttl (x) = ttl (y) by (9), and finally x = y. Lemma 3.14 implies that at most one element is deleted from SP at each iteration. To perform this deletion in O(1) time, we need an additional data structure. By BS(x) we denote a linked list of maximal segments of 1's in the binary representation of x. For example, the binary representation of x = 12345 and BS(x) are as follows:  Thus, if we support one list BS which is equal to BS(i) at the end of the ith iteration, we have β(i). If I(a) should be deleted from SP at this iteration, then β(a) = β(i) (see Lemma 3.14). The following lemma is trivial. if v = sp then 8: sp ← next(sp) 9: delete v; delete f irst(QU (β(i))) 10: add pointer to f irst(SP ) to QU (β(i)) 11: read S[i]; compute I(i + 1) from I; I ← I(i + 1) 12: sp ← previous(sp) if exists 13: while i − sp.i + 1 ≤ answer.len and sp = last(SP ) do 14: sp ← next(sp) 15: for all existing v in {sp, next(sp), next(next(sp))} do 16: if S[v.i..i] is a palindrome and answer.len < i−v.i+1 then 17: Proof of Theorem 3.6. After every iteration, Algorithm M has the same list SP (see Fig. 1) as Algorithm MBasic, because these algorithms add and delete the same elements. Due to Lemma 3.13, Algorithm M returns the same answer as Algorithm MBasic. Hence by Proposition 3.11 Algorithm M finds a palindrome of required length. Further, Algorithm M supports the list BS of size O(log n) and the array QU containing O(log n) queues of total size equal to the size of SP . Hence, it uses O( log(nε) ε ) space in total by Lemma 3.10. The cycle in lines 13-14 performs at most three iterations. Indeed, let z be the value of sp after the previous iteration. Then this cycle starts with sp = previous(z) (or with sp = z if z is the first element of SP ) and ends with sp = next(next(z)) at the latest. By Lemma 3.15, both BS(i) and β(i) can be computed in O(1) time. Therefore, each iteration takes O(1) time.
Remark Since for n −0.99 ≤ ε ≤ 1 the classes O log n log(1+ε) and O log(nε) ε coincide, Algorithm M uses space within a log n factor from the lower bound of Theorem 2.7. Furthermore, for an arbitrarily slowly growing function ϕ Algorithm M uses o(n) space whenever ε = ϕ(n) n .
We transform Algorithm M into real-time Algorithm M' which solves LPS(S) with the multiplicative error ε > 1 using O log n log(1+ε) space. The basic idea of transformation is to replace all binary representations with those in base proportional to 1 + ε, and thus shrink the size of the lists SP and BS.
First, we assume without loss of generality that ε ≥ 7, as otherwise we can fix ε = 1 and apply Algorithm M. Fix k ≤ 1 2 (1 + ε) as the largest such even integer (in particular, k ≥ 4). Let β (i) be the position of the rightmost non-zero digit in the k-ary representation of i. We define The list SP is the analog of the list SP from Sect. 3.2. It contains, after ith iteration, the tuples I(j) for all positions j ≤ i such that j + ttl (j) > i. Similar to (10), we partition the range (0; i] into intervals and then count the elements of SP in these intervals. The intervals are, right to left, For convenience, we enumerate the intervals starting with 0. Proof. The 0th interval contains exactly 4 elements. For any j = 1, . . . , m+1, an element x of the jth interval is in SP if and only if its position is divisible by k j ; see (11). The length of this interval is less than 9 2 k j , giving us upper bound of 9 2 = 5 elements. Similarly, if j = m+1, the jth interval has the length 9 2 k j − 9 2 k j−1 and thus contains at least 9 2 k−1 k elements of SP . Since k ≥ 4, the claim follows.
Next we modify Algorithm MBasic, replacing ttl by ttl and SP by SP . . Without loss of generality we assume d ≥ 0, as otherwise L(S) < 4 ≤ ttl (i) and the palindrome S[i..j] will be detected exactly. Since L(S) ≥ 4k d , let a 1 < a 2 < a 3 < a 4 < a 5 be consecutive positions which are multiples of k d (i.e., β (a 1 ), . . . , β (a 5 ) ≥ d) such that a 2 ≤ i+j 2 < a 3 . Then in particular i < a 1 , and there is a palindrome S[a 1 ..(i + j − a 1 )] such that a 3 ≤ (i + j − a 1 ) < a 5 . Since a 1 + ttl (a 1 ) ≥ a 5 , this particular palindrome will be detected by the modified Algorithm MBasic; thus (S) ≥ a 3 − a 1 = 2k d . However, we have L(S) < 4k d+1 , hence L(S) (S) < 2k ≤ (1 + ε). Space complexity follows from bound on size of the list SP , which is at most 5 log n log k = O log n log(1+ε) . To follow the framework from the case of ε ≤ 1, we provide analogous speedup to the checks for palindromes. We adopt the same notion of an element valuable at ith iteration as in Sect. 3.2. First we need the following property, which is a more general analog of Lemma 3.12; an analog of Lemma 3.13 is then proved with its help. Proof. Let c, d belong to the jth interval. Thus they are divisible by k j and d − c = k j . Since a < c, a is divisible by k j as well. One of the numbers d+a 2 , c+a 2 is divisible by k j ; take it as b.
is also a palindrome. Since at the ith iteration the left border of the jth interval was smaller than c, then at the (i − δ)th iteration this border was smaller than b; hence, I(b) was in SP at that iteration, and the palindrome S[b..i − δ] was found. Its length is which is impossible by the definition of answer.len. So S[a..i] is not a palindrome, and the claim follows. Proof. Let a < b < c < d be such that the elements I(d), I(c), I(b) are consecutive in SP and I(a) belongs to SP . Then either b, c or c, d are in the same interval of (12), and thus a is not valuable by Lemma 3.20.

The Case of Short Palindromes
A typical string contains only short palindromes, as Lemma 3.23 below shows (for more on palindromes in random strings, see [16]). Knowing this, it is quite useful to have a deterministic real-time algorithm which finds a longest palindrome exactly if it is "short", otherwise reporting that it is "long". The aim of this section is to describe such an algorithm (Theorem 3.24).
Lemma 3.23. If an input stream S ∈ Σ * is picked up uniformly at random among all strings of length n, where n ≥ |Σ|, then for any positive constant c the probability that S contains a palindrome of length greater than 2(c+1) log n log |Σ| is O(n −c ).

Proof.
A string S contains a palindrome of length greater than m if and only if S contains a palindrome of length m+1 or m+2. The probability P of containing such a palindrome is less than the expected number M of palindromes of length m+1 and m+2 in S. A factor of S of length l is a palindrome with probability 1/|Σ| l/2 ; by linearity of expectation, we have  Proof. To prove Theorem 3.24, we present an algorithm based on the Manacher algorithm [14]. We add two features: work with a sliding window instead of the whole string to satisfy the space requirements and lazy computation to achieve real time. (The fact that the original Manacher algorithm admits a real-time version was shown by Galil [7]; we adjusted Galil's approach to solve LPS.) The details follow.
We say that a palindromic factor S[i.
.j] has center i+j 2 and radius j−i 2 . Thus, odd-length (even-length) palindromes have integer (resp., half integer) centers and radiuses. This looks a bit weird, but allows one to avoid separate processing of these two types of palindromes. Manacher's algorithm computes, in an online fashion, an array of maximal radiuses of palindromes centered at every position of the input string S. A variation, which outputs the length L of the longest palindrome in a string S, is presented as Algorithm EBasic below. This variation is similar to the one of [13]. Here, n stays for the length of the input processed so far, c is the center of the longest suffix-palindrome of the processed string. The array of radiuses Rad has length 2n−1 and its elements are indexed by all integers and half integers from the interval [1, n]. Initially, Rad is filled with zeroes. The left endmarker is added to the string for convenience. After each iteration, the following invariant holds: the element Rad[i] has got its true value if i < c and equals zero if i > c; the value Rad[c] = n − c can increase at the next iteration. Note that the longest palindrome in S coincides with the longest suffix-palindrome of S[1..i] for some i. At the moment when the input stream ends, the algorithm has already found all such suffix-palindromes, so it can stop without filling the rest of the array Rad.
Note that n calls to AddLetter perform at most 3n iterations of the cycle in lines 10-15 (each call performs the first iteration plus zero or more "additional" iterations; the value of c gets increased before each additional iteration and never decreases). So, Algorithm EBasic works in O(n) time but not in real time; for example, reading the last letter of the string a n b requires n iterations of the cycle.
By conditions of the theorem, we are not interested in palindromes of length > m+1. Thus, processing a suffix-palindrome of length m or m+1 we assume that the symbol comparison in line 12 fails. So the procedure AddLetter needs no access to S[i] or Rad[i] whenever i < n − m. Hence we store only recent values of S and Rad and use circular arrays CS and CRad of size O(m) for this purpose. For example, the symbol S[n−i] is stored in CS[(n−i) mod (m+1)] during m+1 successful iterations of the outer cycle (lines 3-6), and then is replaced by S[n−i+m+1]; the same scheme applies to the array Rad. In this way, all elements of S and Rad, needed by Algorithm EBasic, are accessible in constant time. Further, we define c ← c + 0.5 next candidate for the center 16: n ← n + 1 a queue Q of size q for lazy computations; it contains symbols that are read from the input and await processing. Now we describe real-time Algorithm E. It reads input symbols to Q and stops when the end of the input is reached. After reading a symbol, it runs procedure Manacher, requiring the latter to pause after three "inner iterations" (of the cycle in lines [10][11][12][13][14][15]. The procedure reads symbols from Q; if it tries to read from the empty queue, it pauses. When the procedure is called next time, it resumes from the moment it was stopped. Algorithm E returns the value of L after the last call to procedure Manacher. To analyze Algorithm E, consider the value X = q + n − c after some iteration (clearly, this iteration has number q+n) and look at the evolution of X over time. Let ∆f denote the variation of the quantity f at one iteration. Note that ∆(q+n) = 1. Let us describe ∆X. First assume that the iteration contains three inner iterations. Then ∆n = 0, 1, 2 or 3 and, respectively, ∆c = 1.5, 1, 0.5 or 0. Hence If the number of inner iterations is one or two, then q becomes zero (and was 0 or 1 before this iteration); hence ∆n = 1 − ∆q ≥ 1. Then ∆c ≤ 0.5 and finally ∆X > 0. From these conditions on ∆X it follows that ( * ) if the current value of q is positive, then the current value of X is less than the value of X at the moment when q was zero for the last time.
Let X be the previous value of X mentioned in ( * ). Since the difference n − c does not exceed the radius of some palindrome, X ≤ m/2. Since q ≤ X < X , the queue Q uses O(m) space. Therefore the same space bound applies to Algorithm E. It remains to prove that Algorithm E returns the same number L as Algorithm EBasic with a sliding window, in spite of the fact that Algorithm E stops earlier (the content of Q remains unprocessed by procedure Manacher). Suppose that Algorithm E stops with q > 0 after n iterations. Then the longest palindrome that could be found by processing the symbols in Q has the radius X = n + q − c. Now consider the iteration mentioned in ( * ) and let n and c be the values of n and c after it; so X = n −c . Since q was zero after that iteration, procedure Manacher read the symbol S[n ] during it; hence, it tried to extend a suffix-palindrome of S[1..n −1] with the center c ≤ c . If this extension was successful, then a palindrome of radius at least X was found. If it was unsuccessful, then c ≥ c + 1/2 and hence S[1..n −1] has a suffix-palindrome of length at least X − 1/2. Thus, a palindrome of length X ≤ X − 1/2 is not longer than a longest palindrome seen before, and processing the queue cannot change the value of L. Thus, Algorithm E is correct.
The center and the radius of the longest palindrome in S can be updated each time the inequality in line 6 of procedure Manacher holds. Theorem 3.24 is proved.
Remark Lemma 3.23 and Theorem 3.24 show a practical way to solve LPS. Algorithm E is fast and lightweight (2m machine words for the array Rad, m symbols in the sliding window and at most m symbols in the queue; compare to 17 machine words per one tuple I(i) in the Monte Carlo algorithms). So it makes direct sense to run Algorithm M and Algorithm E, both in O(log n) space, in parallel. Then either Algorithm E will give an exact answer (which happens with high probability if the input stream is a "typical" string) or both algorithms will produce approximations: one of fixed length and one with an approximation guarantee (modulo the hash collision).