22. Longest Prefix Suffix
The problem can be found at the following link: Question Link
Problem Description
Given a string of characters, find the length of the longest proper prefix which is also a proper suffix.
Note: Prefix and suffix can be overlapping but they should not be equal to the entire string.
Examples:
Input: str = "abab"
Output: 2
Explanation: "ab" is the longest proper prefix and suffix.
Input: str = "aaaa"
Output: 3
Explanation: "aaa" is the longest proper prefix and suffix.
My Approach
LPS Array Construction:
Use an array
lpsArrwherelpsArr[i]stores the length of the longest proper prefix which is also a proper suffix for the substringstr[0...i].
Initialization:
Start with the first character; the longest prefix suffix for a single character is always 0.
Iterate through the String:
For each character in the string, update the
lpsArr:If the current character matches the character at index
j, incrementjand setlpsArr[i]toj.If there’s a mismatch and
jis not zero, updatejusing the previously calculated values inlpsArr.
Final Answer:
The value at the last index of
lpsArrwill give the length of the longest proper prefix which is also a proper suffix.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(|str|), where |str| is the length of the string, as we only iterate through the string once.
Expected Auxiliary Space Complexity: O(|str|), due to the LPS array that stores prefix-suffix lengths for each substring.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit my LinkedIn: Any Questions. Thank you for your input; together, we strive to create a space where learning is a collaborative endeavor.
⭐ Star this repository if you find it helpful or intriguing! ⭐
📍Visitor Count
Last updated