lps
of the same length as the input string s
with all zeros. This array will hold the length of the longest proper prefix which is also a suffix for the substring s[0:i]
.len
and i
to 0. len
will track the length of the current longest prefix that matches a suffix, and i
will iterate through the string.s[i]
is equal to s[len]
, increment len
and assign lps[i]
to len
. Increment i
.s[i]
is not equal to s[len]
, check if len
is not zero, then update len
to lps[len - 1]
. Otherwise, if len
is zero, assign lps[i]
to zero and increment i
.lps
array will contain the length of the longest happy prefix.s
from the beginning to the length indicated by the last element of the lps
array.