Problem 77: Anchored squares |
When searching, in a divide-and-conquer way, a word for square factor it is natural to look for squares in the product of two square-free words. The problem deals with the latter question and extends to a square-freeness test running in $O(n\log n)$ time on a word of length $n$.
The method based on prefix tables (see Problem 74) achieves the same goal but requires tables of size $O(n)$ while the present solution needs only a few variables in addition to input.
Let $y$ and $z$ be two square-free words. Algorithm Right tests if $yz$ contains a square centred in $z$ only. Other squares in the product can be found symmetrically.
The algorithm examines all possible periods of a square. Given a period $p$ (see picture), it computes the longest common suffix $u'=z[j\dd p-1]$ between $y$ and $z[0\dd p-1]$. Then it checks if $z[0\dd j-1]$ occurs at position $p$ on $z$, scanning $z$ from the right position $k-1$ of the potential square. If it is successful, a square is found.
\begin{algorithmic} \STATE $(p,\mathit{end})\leftarrow (|z|,|z|)$ \WHILE{$p \gt 0$} \STATE $j\leftarrow \min\{q \mid z[q..p-1] \mbox{ suffix of } y\}$ \IF{$j = 0$} \RETURN{True} \ENDIF \STATE $k\leftarrow p+j$ \IF{$k \lt \mathit{end}$} \STATE $\mathit{end}\leftarrow \min\{q \mid z[q..k-1] \mbox{ suffix of } z[0..j-1]\}$ \IF{$\mathit{end} = p$} \RETURN{True} \ENDIF \ENDIF \STATE $p\leftarrow \max\{j-1,\lfloor p/2 \rfloor\}$ \ENDWHILE \RETURN{False} \end{algorithmic}
In Algorithm Right the role of variable $\mathit{end}$ and instructions at lines 7 and 11 are crucial to get the running time announced in the question. Note that it does not depend on the length of $y$.