08. Longest Prefix Suffix
β GFG solution to the Longest Prefix Suffix problem: find the length of longest proper prefix which is also a suffix using KMP's LPS array construction technique. π
The problem can be found at the following link: π Question Link
π§© Problem Description
Given a string s
of lowercase English alphabets, find the length of the longest proper prefix which is also a suffix.
Note: Prefix and suffix can be overlapping but they should not be equal to the entire string.
A proper prefix is a prefix that is not equal to the string itself. Similarly, a proper suffix is a suffix that is not equal to the string itself.
π Examples
Example 1
Input: s = "abab"
Output: 2
Explanation: The string "ab" is the longest prefix and suffix.
Example 2
Input: s = "aabcdaabc"
Output: 4
Explanation: The string "aabc" is the longest prefix and suffix.
Example 3
Input: s = "aaaa"
Output: 3
Explanation: "aaa" is the longest prefix and suffix.
π Constraints
$1 \le s.size() \le 10^6$
s contains only lowercase English alphabets.
β
My Approach
The optimal approach uses the KMP (Knuth-Morris-Pratt) Algorithm's LPS Array Construction technique:
KMP LPS Array Construction
Initialize Variables:
Create an LPS array of size
n
wherelps[i]
stores the length of longest proper prefix which is also suffix for substrings[0...i]
.Use two pointers:
i
(current position) andj
(length of current matching prefix).
Build LPS Array:
Start with
i = 1
andj = 0
(sincelps[0]
is always 0).If characters match (
s[i] == s[j]
), increment both pointers and setlps[i] = j
.If characters don't match and
j > 0
, movej
tolps[j-1]
(fallback position).If characters don't match and
j == 0
, setlps[i] = 0
and incrementi
.
Extract Result:
The answer is
lps[n-1]
which gives the length of longest proper prefix-suffix for the entire string.
Key Insight:
The LPS array construction efficiently handles all overlapping cases by using previously computed values.
Time complexity remains linear due to the amortized analysis of pointer movements.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the length of the string. Although there are nested loops, the inner while loop's total iterations across all outer loop iterations is bounded by n, making it linear overall.
Expected Auxiliary Space Complexity: O(n), as we use an additional LPS array of size n to store the longest proper prefix-suffix lengths.
π§βπ» Code (C++)
class Solution {
public:
int getLPSLength(string &s) {
int n = s.length(), j = 0;
vector<int> lps(n, 0);
for (int i = 1; i < n; ) {
if (s[i] == s[j]) lps[i++] = ++j;
else if (j) j = lps[j - 1];
else i++;
}
return lps[n - 1];
}
};
β Code (Java)
class Solution {
int getLPSLength(String s) {
int n = s.length(), j = 0;
int[] lps = new int[n];
for (int i = 1; i < n; ) {
if (s.charAt(i) == s.charAt(j)) lps[i++] = ++j;
else if (j > 0) j = lps[j - 1];
else i++;
}
return lps[n - 1];
}
}
π Code (Python)
class Solution:
def getLPSLength(self, s):
n, j, lps = len(s), 0, [0] * len(s)
i = 1
while i < n:
if s[i] == s[j]:
j += 1
lps[i] = j
i += 1
elif j:
j = lps[j - 1]
else:
i += 1
return lps[-1]
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated