<p>A string is called a <strong>happy prefix</strong> if is a <strong>non-empty</strong> prefix which is also a suffix (excluding itself).</p>

<p>Given a string <code>s</code>, return <em>the <strong>longest happy prefix</strong> of</em> <code>s</code>. Return an empty string <code>&quot;&quot;</code> if no such prefix exists.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;level&quot;
<strong>Output:</strong> &quot;l&quot;
<strong>Explanation:</strong> s contains 4 prefix excluding itself (&quot;l&quot;, &quot;le&quot;, &quot;lev&quot;, &quot;leve&quot;), and suffix (&quot;l&quot;, &quot;el&quot;, &quot;vel&quot;, &quot;evel&quot;). The largest prefix which is also suffix is given by &quot;l&quot;.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;ababab&quot;
<strong>Output:</strong> &quot;abab&quot;
<strong>Explanation:</strong> &quot;abab&quot; is the largest prefix which is also suffix. They can overlap in the original string.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>
	<li><code>s</code> contains only lowercase English letters.</li>
</ul>

class Solution {
public:
    string longestPrefix(string s) {
        long long p = 31, n = s.size(), M = 1e9 + 7, currPow = 1;
        vector<long long> h(n);
        for (int i = 0; i < n; i++) {
            h[i] = (s[i] - 'a' + 1) * currPow % M;
            if (i > 0) h[i] = (h[i - 1] + h[i]) % M;
            currPow = (currPow * p) % M;
        }
        auto power = [&](long long a, long long b) {
            long long res = 1;
            while (b) {
                if (b & 1) {
                    res = res * a % M;
                }
                a = a * a % M;
                b >>= 1;
            }
            return res;
        };
        // for (auto x : h) cout << x << ' ';
        // cout << '\n';
        for (int i = n - 2; i >= 0; i--) {
            int j = n - 1 - i;
            long long h1 = h[i], h2 = (h[n - 1] - h[j - 1] + M) % M;
            h2 = h2 * power(power(p, j), M - 2) % M;
            // cout << i << ' ' << j << ' ' << h1 << ' ' << h2 << ' ';
            // cout << s.substr(i + 1) << ' ' << s.substr(j, n - j) << '\n';
            if (h1 == h2 && s.substr(0, i + 1) == s.substr(j, n - j)) {
                return s.substr(0, i + 1);
            }
        }
        return "";
    }
};
27330