<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:
    using ll = long long;
    string longestPrefix(string &s)
    {
        // collision aware decremental hash (rolling hash)
        long hash = 0, mul = 1;
        const ll MOD = 1e9 + 7, INVERSE_MOD_26 = 576923081;
        int n = s.size();

        for (int i = 0, j = n - 1; j >= 0; ++i, --j)
        {
            hash = (hash * 26 + s[i] - 'a') % MOD;
            mul = mul * 26 % MOD;
        }
        long h1 = hash, h2 = hash;
        for (int i = 0, j = n - 1; i < n - 1; j--, i++)
        {
            mul = mul * INVERSE_MOD_26 % MOD;
            int left = s[i] - 'a', right = s[j] - 'a';
            h1 = ((h1 - (right)) * INVERSE_MOD_26) % MOD;
            h2 = (MOD + h2 - ((mul * (left)) % MOD)) % MOD;
            if (h1 == h2)
            {
                if (s.compare(0, j, s, i + 1, n - i - 1) == 0)
                    return s.substr(0, j);
            }
        }
        return "";
    }
};
14850