# Longest Happy Prefix in C++

C++Server Side ProgrammingProgramming

Suppose we have a string s, we have to find the longest happy prefix of s. A string is called a happy prefix if is a non-empty prefix which is also a suffix (excluding itself). If there is no such happy prefix, then simply return blank string.

So, if the input is like "madam", then the output will be "m", it has 4 prefixes excluding itself. These are "m", "ma", "mad", "mada" and 4 suffixes like "m", "am", "dam", "adam". The largest prefix which is also suffix is given by "m".

To solve this, we will follow these steps −

• Define a function lps(), this will take s,

• n := size of s

• Define an array ret of size n

• j := 0, i := 1

• while i < n, do −

• if s[i] is same as s[j], then

• ret[i] := j + 1

• (increase i by 1)

• (increase j by 1)

• otherwise when s[i] is not equal to s[j], then −

• if j > 0, then −

• j := ret[j - 1]

• Otherwise

• (increase i by 1)

• return ret

• From the main method do the following −

• n := size of s

• if n is same as 1, then −

• return blank string

• Define an array v = lps(s)

• x := v[n - 1]

• ret := blank string

• for initialize i := 0, when i < x, update (increase i by 1), do −

• ret := ret + s[i]

• return ret

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector <int> lps(string s){
int n = s.size();
vector<int> ret(n);
int j = 0;
int i = 1;
while (i < n) {
if (s[i] == s[j]) {
ret[i] = j + 1;
i++;
j++;
}
else if (s[i] != s[j]) {
if (j > 0)
j = ret[j - 1];
else {
i++;
}
}
}
return ret;
}
string longestPrefix(string s) {
int n = s.size();
if (n == 1)
return "";
vector<int> v = lps(s);
int x = v[n - 1];
string ret = "";
for (int i = 0; i < x; i++) {
ret += s[i];
}
return ret;
}
};
main(){
Solution ob;
}
"madam"
m