<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>

class Solution {
public:
    const long long MOD = 1e5 + 3;
    const long long BASE = 26;
    long long* pow;
    string shortestPalindrome(string s) {
        long long n = s.size();
        vector<long long> pow(n + 1);

        pow[0] = 1;
        for (int i = 1; i < n; ++i)
            pow[i] = (pow[i - 1] * BASE) % MOD;

        vector<long long> hash(n + 1);
        vector<long long> rev_hash(n + 1);

        hash[0] = s[0] - 'a';
        rev_hash[0] = s[0] - 'a';
        for (long long i = 1; i < n; ++i) {
            hash[i] = (hash[i - 1] + ((s[i] - 'a') * pow[i]) % MOD) % MOD;

            rev_hash[i] = (rev_hash[i - 1] * BASE) % MOD;
            rev_hash[i] = (rev_hash[i] + (s[i] - 'a')) % MOD; 
        }

        long long index = 0;
        for (long long i = 0; i < n; ++i) {
            if (hash[i] == rev_hash[i]) index = i;
        }

        string result = "";
        for (long long i = n - 1; i > index; --i)
            result.push_back(s[i]);
        for (long long i = 0; i < n; ++i)
            result.push_back(s[i]);
        return result;
    }
};
13600