Editorial for Waterloo 2025 Fall B - Palindromic Triplets
Submitting an official solution before solving the problem yourself is a bannable offence.
Author:
Given two strings , we let
denote their concatenation,
and
denote the string that results from reversing
.
Suppose is a palindromic triple.
Write
.
We have three cases:
Case 1:
contains the midpoint of
. We again have three cases:
Case 1a:
, where
is an odd length palindrome and
is not the empty string.
Then for
be be a palindrome, we must have
.
Case 1b:
, where
is an odd length palindrome.
Then for
be be a palindrome, we must have
.
Case 1c:
, where
is an odd length palindrome and
is not the empty string.
Then for
be be a palindrome, we must have
. \end{itemize}
Case 2:
contains the midpoint of
. We can write
, where
is an odd length palindrome. We need
.
Case 3:
contains the midpoint of
. We can write
, where
is an odd length palindrome. We need
.
It is clear these cases are disjoint, and it can be checked that they are exhaustive.
To count the number of palindromic triples satisfying Case 1a,
we need to count the number of pairs such that
.
To do so, we will precompute
To build this table, for each
, we can consider all
ways to
write
as a prefix and a suffix
;
then the number of pairs
contributes to
is precisely the number of strings
such that
.
This can be computed in
time by computing rolling hashes for
all strings
and
.
Thus the pre-computation takes time
.
Case 1c is similar, but instead we precompute
which can be done similarly to the previous case.
For Case 1b, we need to compute the number of pairs of strings
where
; this can be done in
time by using our precomputed hashes.
To count the number of palindromic triples satisfying Case 2,
we want to find all pairs such that
.
To do this naïvely, we would try all ways to split
into a
prefix and suffix
and check if there exists
and
via our hashes.
By a classical application of square root decomposition,
we know there are at most
possible
lengths for
, so we only have to check
splits.
Case 3 is similar to Case 2, but mirrored.
Finally, the preprocessing for all the cases can be done in time.
As the string
has
possible midpoints to check,
and the cases can be checked in
, the final time complexity is
Comments