Official

A - ST and TS Palindrome Editorial by evima


Let \(rev(S)\) denote the reversal of \(S\). Additionally, let \(S+S'\) denote the concatenation of \(S\) and \(S'\) in this order.

[1] The case \(K < 2N\)

If \(K < 2N\), the leftmost \(\min(N,\ K)\) characters of \(S'\) must equal \(rev(S)\), and so must the rightmost \(\min(N,\ K)\) characters, so there is at most one string \(S'\) that can potentially satisfy the conditions. You just have to check if it does.

[2] Reduce the case \(2N \leq K\) to [1]

If \(2N \leq K\), similar observations can rephrase the problem as follows.

There is \(S'\ (|S'|=K)\) such that \(S+S',\ S'+S\) are both palindromes

\(\iff\) There is \(S'\ (|S'|=K-2N)\) such that \(S+rev(S)+S'+rev(S),\ rev(S)+S'+rev(S)+S\) are both palindromes

\(\iff\) There is \(S'\ (|S'|=K-2N)\) such that \(rev(S)+S',\ S'+rev(S)\) are both palindromes

\(\iff\) There is \(S'\ (|S'|=K-2N)\) such that \(rev(rev(S)+S'),\ rev(S'+rev(S))\) are both palindromes

\(\iff\) There is \(S'\ (|S'|=K-2N)\) such that \(rev(S')+S,\ S+rev(S')\) are both palindromes

\(\iff\) There is \(S'\ (|S'|=K-2N)\) such that \(S'+S,\ S+S'\) are both palindromes

Therefore, one may replace \(K\) with \(K \bmod 2N\), reducing the problem to the case \(K < 2N\).

Therefore, the problem can be solved in \(O(N)\) time per test case.

posted:
last update: