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

using ll = long long;


// int main(){
// 	string text;
// 	string pattern;
// 	cin>>text>>pattern;
// 	kmp(text,pattern);
// }

class Solution {
public:

vector<ll> find_lps(string& pattern){
    //longest proper prefix which is also a suffix in the patter
    int m = pattern.length(),len=0,i=1;
    vector<ll> lps(m,0);
    while(i<m){
        if(pattern[i]==pattern[len]){
            lps[i]=len+1;
            i++;len++;
        }
        else{
            if(len!=0){
                len = lps[len-1];
            }
            else{
                lps[i]=0;
                i++;
            }
        }
    }
    return lps;

}

// void kmp(string& text,string& pattern){
// 	int n = text.length(),m=pattern.length(),i=0,j=0;
// 	vector<int> lps = find_lps(pattern);
// 	while(i<n){
// 		if(text[i]==pattern[j]){
// 			i++;j++;
// 		}
// 		else{//mismatch
// 			if(j-1>=0)j=lps[j-1];
// 			else i++;//mismatch at first position itself
// 		}
// 		// if (j==m)return false;//found
// 		if(j==m){
// 			cout<<(i-j)<<" ";
// 			j = lps[j-1];
// 		}
// 	}
// }


    string longestPrefix(string& s) {
        auto lps = find_lps(s);
        return s.substr(0,lps[s.length()-1]);
    }
};
24470