<p>You are given a string <code>s</code>. You can convert <code>s</code> to a <span data-keyword="palindrome-string">palindrome</span> by adding characters in front of it.</p>

<p>Return <em>the shortest palindrome you can find by performing this transformation</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> s = "aacecaaa"
<strong>Output:</strong> "aaacecaaa"
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> s = "abcd"
<strong>Output:</strong> "dcbabcd"
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li>
	<li><code>s</code> consists of lowercase English letters only.</li>
</ul>

#pragma GCC optimize("Ofast,inline,unroll-loops,fast-math")
#pragma GCC target("avx,avx2,fma")

const long MOD = 1e9 + 7;
const long X = 31;

class Solution {
public:
    string shortestPalindrome(const string &s) {
        const int N = s.length();
        if (N < 2) return s;
        long hleft = 0;
        long hright = 0;
        long xn = 1;
        int len = 0;
        for (int i = 0; i < N; ++i) {
            const long v = (s[i] - 'a');
            hleft = ((hleft * X) % MOD + v) % MOD;
            hright = ((v * xn) % MOD + hright) % MOD;
            xn = (xn * X) % MOD;
            len = (hleft == hright) ? i + 1 : len;
        }
        if (len == N) return s;
        const int tail = N - len;

        string res(tail + N, '\0');

        copy(s.begin() + len, s.end(), res.begin());
        reverse(res.begin(), res.begin() + tail);
        copy(s.begin(), s.end(), res.begin() + tail);

        return res;
    }
};
9000