<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) {
        int n=s.length();
        vector<int> lps(n, 0);  // LPS array
    
    
    int len = 0;  
    for (int i = 1; i < n; ++i) {
        while (len > 0 && s[i] != s[len]) {
            len = lps[len - 1];
        }
        if (s[i] == s[len]) {
            len++;
        }
        lps[i] = len;
    }

    // The longest happy prefix will be the prefix of length lps[n-1]
    return s.substr(0, lps[n - 1]);
        // 74
       /* int n = s.length();
        long long prefixHash = 0, suffixHash = 0, base = 31, mod = 1e9 + 7;
        long long power = 1;
        int result = 0;

        // Calculate prefix and suffix hashes
        for (int i = 0, j = n - 1; i < n - 1; ++i, --j) {
            // Calculate prefix hash (from left to right)
            prefixHash = (prefixHash * base + (s[i] - 'a' + 1)) % mod;

            // Calculate suffix hash (from right to left)
            suffixHash = (suffixHash + (s[j] - 'a' + 1) * power) % mod;

            // Update the power for the suffix hash (base^(i+1) % mod)
            power = (power * base) % mod;

            // If prefix hash matches suffix hash, update the result
            cout<<suffixHash<<" "<<prefixHash<<endl;
            if (prefixHash == suffixHash) {
                result = i + 1;
            }
        }
        return s.substr(0,result);
        // 60
        long long a = s.length();

        for(long long i=a-1;i>0;i--)
        {
            if(s.substr(0,i)==s.substr(a-i,i))
            {
                return(s.substr(0,i));
            }
        }
        return "";*/

    }
};
20570